Python 从数组中查找字符串中的单词

Python 从数组中查找字符串中的单词,python,Python,我正在使用一个twitterapi,正在扫描tweet,看看它们是否包含一个名为“special”的数组中的单词。下面的代码似乎工作正常,但仅指示何时找到匹配项。如何让它同时显示匹配的特定单词和包含该单词的字符串 if any(word in tweet.body for word in special): print "match found" 我想要的是类似于在推特“我是鲍勃”中发现的鲍勃这个词的东西 干杯此代码将打印给定tweet的所有匹配单词 def f

我正在使用一个twitterapi,正在扫描tweet,看看它们是否包含一个名为“special”的数组中的单词。下面的代码似乎工作正常,但仅指示何时找到匹配项。如何让它同时显示匹配的特定单词和包含该单词的字符串

if any(word in tweet.body for word in special):
                print "match found"
我想要的是类似于在推特“我是鲍勃”中发现的鲍勃这个词的东西


干杯

此代码将打印给定tweet的所有匹配单词

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
    )
根据注释中的请求更新了代码段

import re

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

适当地使用regx
仅当您需要不区分大小写的搜索时才使用re.IGNORECASE。

只需自己编写明显的for循环,这样您就可以访问找到的关键字。这行不通。至少在我的Python版本2.7.13中,name word在print语句的范围内,而在Python 3中肯定不是。如果是的话,我想它只会打印出所有匹配词的第一个词。没错,我太匆忙了。谢谢!这很有效。有没有一种简单的方法可以让这个匹配只使用正则表达式之外的精确匹配?。我注意到特殊的单词“one”将与“phone”匹配。使用正则表达式匹配精确文本。希望这有帮助。
import re

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

for word in special:
    reg_object = re.search(word, tweet_body, re.IGNORECASE)
    if reg_object:
        print(reg_object.group(), word) # this will get you the exact string 
        # That matched in the tweet body and your key string.