How to calculate the occurrences of words in a list with Python

2 Answers

0 votes
from collections import Counter

occurrences = Counter()
for word in ['aaa', 'bbb', 'bbb', 'ccc', 'aaa', 'aaa', 'ddd']:
    occurrences[word] += 1

print(occurrences)

'''
run:
 
Counter({'aaa': 3, 'bbb': 2, 'ddd': 1, 'ccc': 1})

'''

 



answered Nov 4, 2018 by avibootz
0 votes
from collections import Counter

lst = ['aaa', 'bbb', 'bbb', 'ccc', 'aaa', 'aaa', 'ddd']

occurrences = Counter()
for word in lst:
    occurrences[word] += 1

for item in occurrences.items():
    print(item[0], ":", item[1])

'''
run:
 
aaa : 3
ccc : 1
bbb : 2
ddd : 1

'''

 



answered Nov 4, 2018 by avibootz
...