在字符串中查找数组中的单词

时间:2018-01-11 12:22:50

标签: python

我正在使用Twitter API并正在扫描推文,看看它们是否包含一个名为“特殊”数组的单词。以下代码似乎工作正常,但仅指示何时找到匹配项。我如何让它显示匹配的特定单词,以及包含该单词的字符串?

if any(word in tweet.body for word in special):
                print "match found"

我喜欢的是" BOB这个词在推文中被发现'我是BOB'"

干杯

3 个答案:

答案 0 :(得分:0)

此代码将打印给定推文的所有匹配单词。

def find_words_in_tweet(tweet, words):
    return [word for word in words if word in tweet]

special = ['your', 'words']
for tweet in tweets:
    words = find_words_in_tweet(tweet.body, special)
    print "Matched words: {words} in tweet: {tweet}.".format(
        words=words.join(', '), tweet=tweet.body
    )

答案 1 :(得分:0)

for word in special:
    if word in tweet.body:
        print "Matched {0}. In string: {1}.".format(word, tweet.body)

根据评论中的请求更新了代码段

import re

word = 'one'
result = re.search(r'\b'+ word + r'\b', 'phone hello')
if result:
    print "Found!"
else:
    print "No Match!!!"

<强>结果:

No Match!!!

答案 2 :(得分:0)

适当使用regx

for

仅在需要不区分大小写的搜索时才使用re.IGNORECASE。