我正在尝试从.txt文件中收集列表,对结果进行统计,然后像这样打印出来
Bones found:
Ankylosaurus: 3
Pachycephalosaurus: 1
Tyrannosaurus Rex: 1
Struthiomimus: 2
点文本文件的示例是
Ankylosaurus
Pachycephalosaurus
Ankylosaurus
Tyrannosaurus Rex
Ankylosaurus
Struthiomimus
Struthiomimus
我当前的代码从.txt文件中提取所有名称,除了im完全卡在那里之外
frequency = {}
for line in open('bones.txt'):
bones = line.split()
print(bones)
请帮忙吗?
答案 0 :(得分:0)
将每行存储为字典键(如果行不在dict中,则初始化为0)并增加值:
frequency = {}
for line in open('bones.txt'):
if line not in frequency:
frequency[line] = 0
frequency[line] += 1
for k, v in frequency.items():
print('{}: {}'.format(k, v))
答案 1 :(得分:0)
您可以使用集合库中的Counter函数来获取此信息。
from collections import Counter
f=open('bones.txt','r')
ls=f.readlines()
s=dict(Counter(ls))
for k in s.keys():
print ('{}:{}'.format(k,s[k]))
答案 2 :(得分:0)
使用collections.defaultdict
例如:
from collections import defaultdict
d = defaultdict(int)
with open(filename) as infile: #Open File
for line in infile: #Iterate Each Line
d[line.strip()] += 1
print("Bones found:")
for k, v in d.items():
print("{}: {}".format(k, v))
输出:
Bones found:
Struthiomimus: 2
Pachycephalosaurus: 1
Ankylosaurus: 3
Tyrannosaurus Rex: 1