-2

I'm using a twitter API and are scanning tweets to see if they contain a word which is in an array named 'special'. The following code appears to work fine, but only indicates when it finds a match. How do I also get it to show both the particular word that matched, and the string that the word was contained in?

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

What I'd like is something along the lines of "the word BOB was found in the tweet 'I am BOB'"

Cheers

reti
  • 23
  • 2

3 Answers3

0

This code will print all matched words for given 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
    )
Rafał Łużyński
  • 7,083
  • 5
  • 26
  • 38
  • That won't work. The name `word` is [not defined](https://stackoverflow.com/questions/4198906/python-list-comprehension-rebind-names-even-after-scope-of-comprehension-is-thi/4199355#4199355) in the scope of the `print` statement (at least in my Python version, 2.7.13, and definitely not in Python 3). And if it were, I think it would only print the first word of all that matched. – mkrieger1 Jan 11 '18 at 12:31
  • True, I was too hasty. Edited. – Rafał Łużyński Jan 11 '18 at 12:38
0
for word in special:
    if word in tweet.body:
        print "Matched {0}. In string: {1}.".format(word, tweet.body)

Updated snippet as per request in comment

import re

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

Result:

No Match!!!
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • Thanks! This works well. Is there an easy way of having this match only exact matches (short of using regex?). I notice that the special word 'one' will match in 'phone' etc – reti Jan 11 '18 at 14:50
  • Updated solution. Use regex to match exact text. Hope this helps. – Rakesh Jan 11 '18 at 15:42
0

Use regx appropriately

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.

use re.IGNORECASE only if you need case insensitive search.

Vipul Vishnu av
  • 486
  • 1
  • 5
  • 15