2 回答

TA貢獻1998條經驗 獲得超6個贊
擁有一個集合版本retirements_word_list(為了有效地包括測試)然后循環句子中的單詞,檢查該集合中的包含情況可能更方便,而不是相反:
retirement_words_list = ['match','matching','401k','retirement','retire','rsu','rrsp']
retirement_words_set = set(retirement_words_list)
進而
if any(word in retirement_words_list for word in sentence.lower().split()):
# .... etc ....
您的代碼只是檢查 in 中的任何單詞是否retirement_words_list是句子的子字符串,但實際上您必須尋找整個單詞匹配,否則將 and 包含'matching'在'retirement'列表中是沒有意義的,因為'match'and'retire'已經包含在內。因此使用split- 以及我們也可以反轉邏輯的原因。
注意:您可能需要進行一些進一步的更改,因為您的函數word_checker有一個名為的參數row,但它不使用該參數??赡苣阆胱龅氖虑槭沁@樣的:
def word_checker(sentence):
if any(word in retirement_words_list for word in sentence.lower().split()):
return '401k/Retirement'
else:
return 'Other'
和:
df['topic'] = df['comments'].apply(word_checker,axis=1)
其中sentence是該列中每一行的內容comments。

TA貢獻1797條經驗 獲得超6個贊
這個簡化版本(沒有正則表達式)不起作用嗎?
if any(word in sentence.lower() for word in retirement_words_list):
添加回答
舉報