Python 检查列表中的任何字符串是否出现在较大的字符串上

Python 检查列表中的任何字符串是否出现在较大的字符串上,python,loops,Python,Loops,我有一个字符串列表。我想检查该列表中的任何字符串是否出现在保存在字符串变量上的较大文档上 我知道这可以很容易地用一个循环来完成,但是我会做很多次这个操作(除此之外还有另一个循环),所以我想知道是否有更有效的方法来代替for循环 我的方法是: main_words = ... # List of words I want to check tweet = ... # String containing the text I want to check for word appearance fo

我有一个字符串列表。我想检查该列表中的任何字符串是否出现在保存在字符串变量上的较大文档上

我知道这可以很容易地用一个循环来完成,但是我会做很多次这个操作(除此之外还有另一个循环),所以我想知道是否有更有效的方法来代替for循环

我的方法是:

main_words = ... # List of words I want to check
tweet = ... # String containing the text I want to check for word appearance

for word in main_words:
    if word in tweet:
        .......

可以使用集合获取以下信息:

text = """I have a list of strings. I would like to check if any of the strings of 
that list appears on a bigger document saved on a string var.

I know this can easily be done with a loop, but I will be doing this operation so 
many times (and another loops apart of this) so I was wondering if there is any
more efficient way to do it instead of a for loop."""

words = set(["would","this","do","if","supercalifragelisticexpialigetic"])

text_words = text.split()

# show all that are in it
print(words.intersection(text_words))   # words & set(text_words)
# show all that are not in it
print(words.difference(text_words))     # words - set(text_words)
输出:

set(['this', 'do', 'would', 'if'])               # words & set(text_words)
set(['supercalifragelisticexpialigetic'])        # words - set(text_words)
do 1
would 1
supercalifragelisticexpialigetic None
if 2
this 2

要获得计数,请执行以下操作:

from collections import Counter

counted = Counter(text_words)

for w in words:
    print(w, counted.get(w))
输出:

set(['this', 'do', 'would', 'if'])               # words & set(text_words)
set(['supercalifragelisticexpialigetic'])        # words - set(text_words)
do 1
would 1
supercalifragelisticexpialigetic None
if 2
this 2

如果“biggeer string list”中的“string”:“biggeer string list”,你可以提到你的方法(code)
。count(string)
@lazarus对不起,我刚刚添加了我的想法问题不是循环,而是你的数据结构。使用setI不清楚您想要的输出。你的措辞暗示了一个简单的布尔结果,但讨论的重点是返回所有这些单词。请澄清。您截断的代码示例无法指定当前的问题。