猿问

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

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


我知道这可以通过循环轻松完成,但我将多次执行此操作(以及除此之外的另一个循环),所以我想知道是否有更有效的方法来代替 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:

        .......



翻过高山走不出你
浏览 155回答 1
1回答

慕村225694

您可以使用集合来获取此信息: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 anymore 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 itprint(words.intersection(text_words))   # words & set(text_words)# show all that are not in itprint(words.difference(text_words))     # words - set(text_words)输出:set(['this', 'do', 'would', 'if'])               # words & set(text_words)set(['supercalifragelisticexpialigetic'])        # words - set(text_words)要获得计数,请执行以下操作:from collections import Countercounted = Counter(text_words)for w in words:    print(w, counted.get(w))输出:do 1would 1supercalifragelisticexpialigetic Noneif 2this 2
随时随地看视频慕课网APP

相关分类

Python
我要回答