【发布时间】: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