python-3.x - 在python中使用count提取包含特定单词的句子
问题描述
我有一个很长的文字。我只想提取包含列表中至少一个单词的句子。
list1 = ["apple", "orange", "tomato"...]
text = "I would love an apple. It is a nice day. How are you? Tasty orange..."
我想过做这样的事情:
sentences_with_fruits = []
for sentence in split_into_sentences(text):
if sentence.count(list1) > 0:
sentences_with_word.append(sentence)
我收到以下错误:
必须是 str,而不是列表。
关于如何解决这个问题或获得相同结果的更好方法的任何想法?
解决方案
您还可以使用 NLTK 库中的单词和句子标记器。
from nltk.tokenize import word_tokenize, sent_tokenize
list1 = ["apple", "orange", "tomato"]
text = "I would love an apple. It is a nice day. How are you? Tasty orange..."
sentences_with_word = []
for sen in sent_tokenize(text):
l = word_tokenize(sen)
if len(set(l).intersection(list1))>0:
sentences_with_word.append(sen)
推荐阅读
- python - 如何对列表中的二维数组对求和
- android - 如何实现启动画面的夜间模式?
- angular - 无法读取 ngAfterViewInit 中未定义的属性“createComponent”
- python - Python 标准库不受 pyc 重写之战的影响
- selenium-webdriver - 如何使用机器人框架单击 iframe 内的元素?
- python - 为什么我不能在 statsmodels.formula.api 回归中使用 Python Pandas int 类型(如 Int8Dtype)?
- python - 有没有办法在给定包含python中的节点和权重的networkx图的情况下创建自定义归一化numpy数组
- jquery - 一个函数中有两件事,其中一个必须等待
- python - strip() 考虑什么空白?
- javascript - 检测登录凭据是否保存在 Chrome 扩展程序中的浏览器中