【问题标题】:Extracting sentences which contain specific words using count in python在python中使用count提取包含特定单词的句子
【发布时间】:2020-05-16 16:56:29
【问题描述】:

我的文字很长。我只想提取包含列表中至少一个单词的句子。

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,而不是 list。

关于如何解决这个问题或获得相同结果的更好方法的任何想法?

【问题讨论】:

  • split_into_sentences 返回什么?还要添加完整的回溯。它告诉我们的不仅仅是“必须是 str,而不是 list”。
  • split_into_sentences 从文本中返回句子。
  • 这是有道理的——但你确定没有必要提供minimal reproducible example吗?我评论的第二部分呢?它将帮助我们帮助您。

标签: python-3.x nlp


【解决方案1】:

您还可以使用 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-08
    • 2013-09-02
    • 2014-07-11
    • 2015-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多