python - 如何使用 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
解决方案
如果您想知道句子中是否有确切的单词,您应该检查单词前后是否有空格。
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)
推荐阅读
- java - REQUIRES_NEW:Spring 外部事务回滚,而不是在内部回滚时持久化
- python - 熊猫数据框:从一组行中汇总单元格数据,存储在一个新列中
- python - 在python中组合2个修剪的音频文件不起作用
- python - 使用 hashlib 在 python 中加密
- c# - 如何使用 NSubstitute 模拟带有多个附件的 Outlook.MailItem?
- python - 从函数返回 matplotlib 图/图形并稍后保存
- c# - 如何从 ALT + TAB 隐藏和显示表单
- python - 数据框中新创建的列需要根据条件更新来自另一列的值
- java - 如何用 Java 数组解决这个算法问题?
- c++ - 构造函数有什么用?