Python collections.Counter用法
简单来说Counter就是一个计数器,比如统计一篇文章中每个单词出现的频率
from collections import Counter
colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
c = Counter(colors)
list1=[('UNK',1)]
list1.extend(c.most_common(2))
list1
[(‘UNK’, 1), (‘blue’, 3), (‘red’, 2)]
这里将其统计成列表的形式
c.most_common(2)
[(‘blue’, 3), (‘red’, 2)]
c
Counter({‘red’: 2, ‘blue’: 3, ‘green’: 1})
print(dict(c))
{‘red’: 2, ‘blue’: 3, ‘green’: 1}
只是Counter而没有most_common时可以保存为字典