我有这样的数据文件:
{'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:
在此之后,我不知道如何获得元素总数并计算每个元素。 你能救我吗?
答案 0 :(得分: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)