我正在从包含以下内容的文件中获取信息:
1:Record:Place1:Ext12
2:Record:Place2:Ext2
3:Record:Place1:Ext19
4:Record:Place1:Ext12
我试图将诸如Place1和Place2之类的单词存储在字典中作为键,然后计算它们的出现并将整数count
作为值分别存储到这些键。
file = open('./Records.txt', mode='r')
d_file = file.read()
location = dict()
count = 0
for item in d_file.splitlines():
items = item.split(':')
key = items[2]
if key == items[2]:
count += 1
location[key] = count
print(location)
集合模块中有Counter功能。 (单击以阅读官方文档)
它确实满足您的要求。
from collections import Counter
keys = [lst[2] for lst in item.split(':') for item in d_file.splitlines()]
print(Counter(keys))
在上面的片段中,根据您的格式列出了所有关键出现的列表,然后打印出现次数的字典。