Search code examples
pythonstringtwittercountercanopy

How to compare strings in multiple lists in Python?


I have a Twitter app that combs for tweets about trending topics. It makes a .txt file (called 'words') that parses every single word in all of the tweets as a string in a list.

Currently, to compare each word in the twitter list to a list of "positive" words, I have:

def p_count(l): #list of strings is object called upon
    total = 0
    for w in l: #for each word in twitter 'words' list
        for x in p_words: #for each word in "positive" words list
            if w == x: #compare twitter word to x positive word
                total += 1
    return total
print p_count(words)

I am getting a result of 0, however I know that there are words like 'humble' and 'strong' that appear in both lists. I am using Enthought Canopy. Any tips?


Solution

  • Your code looks fine.

    The problem could have to do with your text file.

    When you retrieve words from a textfile, Python could save those with an '\0' or '\n' at the end. This could be a reason why your words aren't equal.

    Another reason could have to do with capital letters, punctuations, spaces, ...

    Your best bet would be to print 'w' and 'x'. This way you should easily see why they don't match.

    Hope this helps you.