亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

翻過高山走不出你 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 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號