【发布时间】:2019-04-21 06:58:16
【问题描述】:
所以我正在尝试为自己制作一个小脚本,其中我有一个或多个单词,并且应该在一个随机句子中找到所有匹配的单词。
等:
Sentence1 = "Hello, I am new here and I hope I will be able to help and get helped from Stackoverflow"
Sentence2 = "Is it beautiful weather"
Sentence3 = "I hope it wont be snowing here soon"
Sentence4 = "How is the weather"
Words = ['I+be', 'it+weather']
输出应该是这样的
Hello, I am new here and I hope I will be able to help and get helped from Stackoverflow
Is it beautiful weather
I hope it wont be snowing here soon
而且它不打印第一个和最后一个的原因是它不包含I和Be和it和天气
所以我的问题基本上是如何使每个 + 或任何其他特殊字符,如关键字 1 + 关键字 2 + n(可以从 1 到 n 个单词)并比较这些单词是否在句子中
所以我尝试编写的代码类似于
Sentence = [
"Hello, I am new here and I hope I will be able to help and get helped from Stackoverflow",
"Is it beautiful weather", "I hope it wont be snowing here soon",
"How is the weather"]
Words = ['I', 'it+weather']
for loop_word in Words:
for loop_setence in Sentence:
if loop_word in loop_setence:
print(loop_setence)
break
但是现在它只打印出第一句话,因为我现在将单词更改为 I。
我想要做的是,包含超过 1 个单词的单词应该在 etc I+be 之间添加一个特殊字符,所以每当句子中有 I 和 Be 时,它应该打印它找到了那个句子- 否则不打印任何内容。
所以我要问你的问题是,我希望如何继续我的观点:)?
【问题讨论】:
-
'it+weather' in sentence精确搜索此字符串:'it+weather'不存在。 -
第一句包含I和be,应该在输出中吗?
-
@MichaelButscher 哦,是的,这是正确的,我想我需要做一些事情,只要单词中有 +。它应该把它当作我相信的两个词。但不应将其视为
it和weather两个不同的分隔词,例如我会执行 `['it', 'weather'] -
@DanielMesejo 哦,我的错!是的,因为那句话中有一个
I and Be。 -
如果这不是一个简单的练习,您应该使用适当的 NLP 工具而不是破解经典问题。
标签: python string loops if-statement