首页 > 解决方案 > 逐句查找文本中的关键字

问题描述

我正在尝试使用 Python 来搜索句子中的关键字。我发现 Chris_Rands 提供的一种编码非常有用,但我想更改输出格式。这是代码及其输出,然后是我希望新输出的样子。

您能否建议更改代码以创建新输出?

来自 Chris_Rands 的原始代码

sentences = "My name is sing song. I am a mother. I am happy. You sing like my mother".split(".")
search_keywords=['mother','sing','song']

for sentence in sentences:
    print("{} key words in sentence:".format(sum(1 for word in search_keywords if word in sentence)))
    for word in search_keywords:
        if word in sentence:
          print(word)
    print(sentence + "\n")

Chris_Rands 的输出:

2 key words in sentence:
My name is sing song

1 key words in sentence:
 I am a mother

0 key words in sentence:
 I am happy

2 key words in sentence:
 You sing like my mother

我想知道如何在结果中打印那些“关键字”,所以结果将如下所示:

期望的输出

2 key words in sentence: sing song
My name is sing song

1 key words in sentence: mother
 I am a mother

0 key words in sentence:
 I am happy

2 key words in sentence: sing mother
 You sing like my mother

标签: pythonpython-3.x

解决方案


这可以通过为每个句子附加到一个新定义的列表来实现。

解决方案

for sentence in sentences:
    lst = []
    for word in search_keywords:
        if word in sentence:
            lst.append(word)
    print('{0} key word(s) in sentence: {1}'.format(len(lst), ', '.join(lst)))
    print(sentence + "\n")

结果

2 key word(s) in sentence: sing, song
My name is sing song

1 key word(s) in sentence: mother
 I am a mother

0 key word(s) in sentence: 
 I am happy

2 key word(s) in sentence: mother, sing
 You sing like my mother

解释

  • 为每个句子定义一个新列表。
  • 用于list.append在匹配单词的位置追加。
  • 用于str.format以所需格式打印输出。

推荐阅读