繁体   English   中英

python中字典中每个元素的总计

[英]Total of each element in dictionary by python

我有这样的数据文件:

{'one', 'four', 'two', 'eight'}
{'two', 'three', 'seven', 'eight'}

我想获取元素总数并计算每个元素。 结果如下:

total of element: 8
one: 1, two: 2, eight: 2, seven: 1, three: 1, four: 1

这是我的代码:

with open("data.json") as f:
     for line in f:
         result = json.loads(line)
         if 'text' in result.keys():
             response = result['text'] 
             words = response.encode("utf-8").split()
        list={}
        for word in words:

在此之后,我不知道如何获取元素总数并计算每个元素。 你可以帮帮我吗?

您可以使用collections.Counter

import collections

counter = collections.Counter()

with open("data.json") as f:
    for line in f:
        result = json.loads(line)
        if 'text' in result.keys():
            response = result['text']
            words = response.encode("utf-8").split()
            counter.update(words)
print(counter)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM