【问题标题】:Finding keywords in text by sentence逐句查找文本中的关键字
【发布时间】:2018-05-11 03:23:35
【问题描述】:

我正在尝试使用 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

【问题讨论】:

  • 您需要 (1) 学习 Python (2) 了解给定代码的作用 (3) 思考您的程序应该如何工作 (4) 编写代码。
  • 说真的,这样的问题对于Stack Overflow 来说过于宽泛(而且离题),因为不清楚解决方案的哪一部分您不能理解,我们无法将整个 Python 文档复制并粘贴到答案中。
  • 以下答案有帮助吗?如果是这样,请随时接受或要求澄清。

标签: python python-3.x


【解决方案1】:

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

解决方案

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 以所需格式打印输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-13
    • 2013-03-01
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多