使用字典统计词频:
#统计词频
colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
result = {}
for color in colors:
if result.get(color)==None: # if color not in result
result[color]=1
else:
result[color]+=1
print (result)
#{'red': 2, 'blue': 3, 'green': 1}
使用Count统计词频
from collections import Counter
colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
c = Counter(colors)
print (dict(c))
#{'red': 2, 'blue': 3, 'green': 1}
可以往Count
类里面传进字符串,元组,字典,列表等等:
c = Counter('gallahad') # 传进字符串
c = Counter({'red': 4, 'blue': 2}) #