为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

翻过高山走不出你 2021-12-29 10:40:53
我有一个字符串列表。我想检查该列表中的任何字符串是否出现在保存在字符串 var 中的更大文档中。我知道这可以通过循环轻松完成,但我将多次执行此操作(以及除此之外的另一个循环),所以我想知道是否有更有效的方法来代替 for 循环。我的方法是这样的:main_words = ... # List of words I want to checktweet = ... # String containing the text I want to check for word appearancefor word in main_words:    if word in tweet:        .......
查看完整描述

1 回答

?
慕村225694

TA贡献1880条经验 获得超4个赞

您可以使用集合来获取此信息:


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)

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


from collections import Counter


counted = Counter(text_words)


for w in words:

    print(w, counted.get(w))

输出:


do 1

would 1

supercalifragelisticexpialigetic None

if 2

this 2


查看完整回答
反对 回复 2021-12-29
  • 1 回答
  • 0 关注
  • 154 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号