aki*_*ira 6 python counter dictionary
我想计算一个单词出现在sting列表中的次数.
['this is a red ball','this is another red ball']
Run Code Online (Sandbox Code Playgroud)
我写了以下代码
counts = Counter()
for sentence in lines:
counts.update(word.strip('.,?!"\'').lower() for word in sentence.split())
Run Code Online (Sandbox Code Playgroud)
它给出了以下格式的结果
Counter({'': 6, 'red': 2, 'this': 2, ....})
Run Code Online (Sandbox Code Playgroud)
我怎么才能得到字典?
Rah*_*pta 14
如果字典确实是您想要的,您可以执行以下操作.
dict(counts)
Run Code Online (Sandbox Code Playgroud)
虽然你将在counts变量中进行所有操作,你可以在普通的python字典中做,因为它Counter是.的子类dict.
Counter 只是一个 dict 子类。无需“获取”字典;它是一个字典,支持所有的 dict 操作符和方法(虽然update工作方式略有不同)。
如果由于某种原因,它报告自己是一个 Counter 而不是一个 dict 的事实真的让你感到困扰,你可以counts = dict(counts)将它转换回超类。但没有必要这样做。
| 归档时间: |
|
| 查看次数: |
6548 次 |
| 最近记录: |