我目前正在使用str.contain从序列中提取所需单词。稍后决定使用数据帧来执行相同的操作。
text = pd.Series(['ENTER YOUR PIN NUMBER', 'ORDER READY FOR SHIPPING'])
text.str.contains('PIN', regex=False)
由于SHIPPING也有一个PIN,我得到的输出是,
True
True
dtype: bool
预期输出,
True
False
dtype: bool
如果你想知道一个单词是否在句子中,你应该检查单词前后是否有空格。
def check_word(sentence, word):
return (' ' + word + ' ') in (' ' + sentence + ' ')
list_validate=[]
for sentences in text:
list_validate.append(check_word(sentences, 'PIN'))
它返回:
[True, False]
为了将其概括为要检查的单词列表,而不仅仅是一个,您可以使用
def check_word2(sentence,words):
return any(' ' + word + ' ' in ' '+ sentence+' ' for word in words)