【问题标题】:How to extract sentences of text that contain keywords in list如何提取列表中包含关键字的文本句子
【发布时间】:2021-08-13 04:25:36
【问题描述】:

我正在尝试返回列表中包含“任何”单词的所有句子,但结果仅返回列表中第二个单词的句子。在下面的示例中,我想提取包含通货膨胀和商品的句子,而不仅仅是商品。任何帮助将不胜感激。

text = 'inflation is very high. commodity prices are rising a lot. this is an extra sentence'
words = ['inflation', 'commodity']
for word in words:
    [words.casefold() for words in words] #to ignore cases in text

def extract_word(text):

    return [sentence for sentence in text.split('.') if word in sentence]

extract_word(text)

[' commodity prices are rising a lot']

【问题讨论】:

标签: python


【解决方案1】:

你可以试试这个:

texts = ' commodity prices are rising a lot. some random text. this text contains the word: inflation'
words = ['inflation','commodity']
lst_words = [words.casefold() for words in words] #to ignore cases in text

def found_word(sentence, lst_words):
    return any(word in lst_words for word in sentence.split())

def extract_word(text):
    lst_sentences = []
    for sentence in text.split('.'):
        if found_word(sentence, lst_words):
            lst_sentences.append([sentence + '.'])
    return lst_sentences

extract_word(texts)
# [[' commodity prices are rising a lot.'],
#  [' this text contains the word: inflation.']]

它有点长,但我认为阅读要好得多。

【讨论】:

  • 无需在any(...) 中创建列表。 any() 函数需要一个生成器。要求它创建一个列表会强制在生成器上进行一次完整迭代来创建列表,并在列表上进行另一次迭代以评估 any()
【解决方案2】:

我发现生成器在这些情况下非常方便。

def extract_word(text):
    words = ['inflation', 'commodity']
    sentences = text.split('.')
    for sentence in sentences:
        if any(word in sentence for word in words):
            yield sentence

>>> list(extract_word('inflation is very high. commodity prices are rising a lot. this is an extra sentence'))
['inflation is very high', ' commodity prices are rising a lot']

它可读且易于理解结果是什么。

【讨论】:

    【解决方案3】:

    条件if word in sentence 将检查来自for 循环的迭代器word 是否在sentence 中。由于"commodity"words 列表中的最后一个元素,在for 循环之后,word 将包含字符串"commodity"

    相反,在列表推导语句中,您可以检查words 中的任何元素是否在sentence 中,如下所示:

    text = 'inflation is very high. commodity prices are rising a lot. this is an extra sentence'
    words = ['inflation', 'commodity']
    sentences = [sentence for sentence in text.split(".") if any(
        w.lower() in sentence.lower() for w in words
    )]
    
    print(sentences)
    # >>> ['inflation is very high', ' commodity prices are rising a lot']
    

    【讨论】:

      猜你喜欢
      • 2020-12-02
      • 2017-08-03
      • 1970-01-01
      • 2021-12-28
      • 2021-07-07
      • 2021-01-31
      • 1970-01-01
      • 2010-12-28
      • 1970-01-01
      相关资源
      最近更新 更多