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

Pri*_*yan 0 python dictionary

我有这样的数据文件:

{'one', 'four', 'two', 'eight'}
{'two', 'three', 'seven', 'eight'}
Run Code Online (Sandbox Code Playgroud)

我想获得元素的总数并计算每个元素.结果如下:

total of element: 8
one: 1, two: 2, eight: 2, seven: 1, three: 1, four: 1
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

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:
Run Code Online (Sandbox Code Playgroud)

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

unu*_*tbu 7

你可以使用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)
Run Code Online (Sandbox Code Playgroud)