简体   繁体   中英

Why is my python collections Counter returning 1's?

I have a several lists of words and need a total count of each word.

Two lines:

['ashtonsos', 'i', 'heard', 'you', 'shouldnt', 'trust', 'claires', 'with', 'piercings', 'lol']
['liveaidstyles', 'thank', 'you', 'so', 'much', '\xf0\x9f\x92\x98']

I have imported the collections counter, using the line "from collections import Counter"

And this is my code:

         for word in words:
            if word not in unique_words:
                unique_words.append(word)   
        #print unique_words

            tweet_count = Counter(unique_words) 
            for word in unique_words:
                tweet_count.update()


    for word in tweet_count:
        print word, tweet_count[word]

What that prints is each word followed by a 1, even if the word is repeated. So, basically, the counter isn't counting.

FYI...the '.update()' line...I've also used 'tweet_count += 1'... and it returns the same result.

What am I doing wrong??

Isn't it obvious? You're counting a list of unique_words . Unique, by definition, occurring once.

Try this:

counter = Counter()
for my_list in my_list_of_lists:
    counter += Counter(set(my_list))

modified it to:

        for word in words:
            if word not in AFINN and word not in unique_words:
                unique_words.append(word) 

        for word in unique_words:
            tweet_count[word] = tweet_count.get(word,0) + 1 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM