来自列表的蟒蛇单词



我创建了一个小程序,用于搜索列表中的特定单词。它似乎有效,但我希望它也打印出它找到的单词。

到目前为止,我有这个,但它只返回列表中的第一个单词,即使它不是它找到的单词。

如能提供一些建议,将不胜感激。谢谢

text = 'this is a test'
words =['image', 'is']
if any(k in text for k in words):
      for k in words:
        print (k)
        print ("word found")
        break
else:
    print ("nope")

您只需要这样做(众多变体中的一个(:

print(", ".join(k for k in words if k in text))
请注意

,在循环for k in words中,您只需打印所有单词,而不检查它们是否实际包含在text中。您还需要split text中的元素,以检查结果列表是否包含k 。您想执行以下操作:

for k in words:
    if k in text.split():
        print (k)
        print ("word found")

输出

is
word found

这同样适用于初始条件,如果要初步检查text中是否包含任何单词,则需要拆分单词:

any(k in text.split() for k in words)

但是,请注意,正如@Austin发布的那样,最适合您要做的事情的工具是 sets .您可以通过将交集计算为:

set(text.split()) & set(words)
# {'is'}

在集合中查找有关该主题的更多信息 — 唯一元素的无序集合

也许像这样重组

text = 'this is a test'
words =['image', 'is']
words_found = [word for word in words if word in text]
if len(words_found)>0:
    print(words_found)
else:
    print("nope")
    ```

如果要找到共同元素,我建议使用set

text = 'this is a test'
words = ['image', 'is']
print(set(words).intersection(text.split()))
# {'is'}

试试这个:

text = 'this is a test'
words =['image', 'is']
for k in [w for w in words if w in text]: 
    print (k) 
    print ("word found")

试试这个:

text = 'this is a test'
words =['image', 'is']
found = False
found_words = []
for k in words:
    if k in text:
        found_words.append(k)
        found = True
if found:
    print("words found:", found_words)
else:
    print("nope")

将打印:

words found: ['is']

试试这个。

for i in words:
    if i in text:
        print(i)

最新更新