【发布时间】:2015-12-24 03:22:08
【问题描述】:
我想计算一个单词在 sting 列表中出现的次数。
['this is a red ball','this is another red ball']
我写了以下代码
counts = Counter()
for sentence in lines:
counts.update(word.strip('.,?!"\'').lower() for word in sentence.split())
它给了我以下格式的结果
Counter({'': 6, 'red': 2, 'this': 2, ....})
我怎样才能只得到字典?
【问题讨论】:
-
A
Counter是字典的子类——你可以用前者做的一切,你也可以用后者做。为什么要将其转换为香草字典?但这很容易:dict(counts).
标签: python dictionary counter