简体   繁体   中英

Total of each element in dictionary by python

I have data file like this:

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

I want to get total of element and count each element. The result like this:

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

Here is my code:

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:

After this, I don't know how to get total of element and count each element. could you help me?

You could use a 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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