首页 > 解决方案 > 如何使用 Python 中的列表从熊猫数据框/系列中提取单词?

问题描述

我目前正在使用 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

标签: pythonpandas

解决方案


如果您想知道句子中是否有确切的单词,您应该检查单词前后是否有空格。

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)


推荐阅读