How Do I Count Unique Words Using Counter Library In Python?
Solution 1:
The python Counter class takes an Iterable object as parameter. As you are giving it a String object:
Counter('like baby baby baby ohhh baby baby like nooo')
it will iterate over each character of the string and generate a count for each of the different letters. Thats why you are receiving
Counter({'b': 10, ' ': 8, 'a': 5, 'y': 5, 'o': 4, 'h': 3, 'l': 2, 'i': 2, 'k': 2, 'e': 2, 'n': 1})
back from the class. One alternative would be to pass a list to Counter. This way the Counter class will iterate each of the list elements and create the count you expect.
Counter(['like', 'baby', 'baby', 'baby', 'ohhh', 'baby', 'baby', 'like', 'nooo'])
That could also be simply achived by splitting the string into words using the split method:
Counter('like baby baby baby ohhh baby baby like nooo'.split())
Output
Counter({'baby': 5, 'like': 2, 'ohhh': 1, 'nooo': 1})
Solution 2:
Using the collections.counter you should first split the string into words like so words = 'like baby baby ohhh so forth'.split()
Then feed the words
variable into the counter.
Yes you can do it without collections module (counter object). There are several ways to do it. One of them, probably not the most efficient one is this:
words = 'like baby baby ohhh so forth'.split()
unique_words = set(words) # converting to set gets rid of duplicates
wordcount ={} # an epmty dictfor word in unique_words:
wordcount[word]=0 # set zero counter for each of the wordsfor word in words:
wordcount[word]+= 1 # for each occurrence of a word in the list made fro original string, find that key in dict and increment by 1print(wordcount)
Solution 3:
Try this:
string ='like baby baby baby ohhh baby baby like nooo'
words = string.split()
result= dict()
for w in words:
if result.get(w) ==None:
result[w] =1else:
result[w] +=1for w inresult:
print(w +' -- '+ str(result[w]))
Post a Comment for "How Do I Count Unique Words Using Counter Library In Python?"