skip to Main Content

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

3

Answers


  1. 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
        )
    
    Login or Signup to reply.
  2. 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!!!
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search