Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从计数器对象中提取字典_Python_Dictionary_Counter - Fatal编程技术网

Python 从计数器对象中提取字典

Python 从计数器对象中提取字典,python,dictionary,counter,Python,Dictionary,Counter,我想计算一个单词在列表中出现的次数 ['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,

我想计算一个单词在列表中出现的次数

['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, ....})

我怎么能只得到字典呢?

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


如果出于某种原因,它报告自己是一个计数器而不是dict这一事实真的让您感到困扰,那么您可以执行
counts=dict(counts)
将其转换回超类。但是没有必要这样做。

如果你真的想要一本字典,你可以做以下事情

dict(counts)
尽管您将在
counts
变量中执行所有操作,这可以在普通python字典中执行,因为
Counter
dict
的子类

A是用于计算散列对象的子类


计数器是字典的一个子类,你可以用前者做任何事情,也可以用后者做任何事情。你为什么要把它转换成香草口诀?但这很简单:
dict(counts)
@akira,请用复选标记按钮接受足够的答案。它值得你再重复两次。