#统计词频
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}
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}) # 传进字典
c = Counter(cats=4, dogs=8) # 传进元组
c = Counter(['eggs', 'ham']) # 传进列表
- 如果没有元素的话那么返回
0
(比dict
)要方便的很多
c = Counter(['eggs', 'ham'])
c['bacon'] # 不存在就返回0
#0
c['sausage'] = 0 # counter entry with a zero count
del c['sausage']
c = Counter(a=4, b=2, c=0, d=-2)
list(c.elements())
#['a', 'a', 'a', 'a', 'b', 'b']
- 返回词频最高的
n
个元素.most_common(n)
,如果n
是0那么返回所有的元素
Counter('abracadabra').most_common(3)
#[('a', 5), ('r', 2), ('b', 2)]
c = Counter(a=3, b=1)
d = Counter(a=1, b=2)
c + d # 相加
#Counter({'a': 4, 'b': 3})
c - d # 相减,如果小于等于0,删去
#Counter({'a': 2})
c & d # 求最小
#Counter({'a': 1, 'b': 1})
c | d # 求最大
#Counter({'a': 3, 'b': 2})
- 可以直接用一个列表更新
Counter
,symbols
是一个列表
symbols = self.tokenize(line, add_eos=add_eos)
self.counter.update(symbols)
本文标题:[Collections]Counter使用教程
本文链接:https://www.haomeiwen.com/subject/hyhebqtx.html