从Counter对象中提取字典

时间:2015-09-26 11:25:47

标签: python dictionary counter

我想计算一个单词出现在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, ....})

我怎样才能获得字典?

2 个答案:

答案 0 :(得分:14)

如果字典确实是您想要的,您可以执行以下操作。

dict(counts)

虽然你将在counts变量中拥有所有操作,你可以在普通的python字典中进行操作,因为Counterdict的子类。

来自Counter docs:

  

Counter是用于计算可哈希对象的 dict子类

答案 1 :(得分:4)

Counter只是一个dict子类。没有必要“得到”字典;它一个字典,并支持所有的dict运算符和方法(尽管update的工作方式略有不同)。

如果由于某种原因,它报告自己是一个计数器而不是一个字典真的困扰你,你可以做counts = dict(counts)将它转换回超类。但是没有必要这样做。

相关问题