我的代码应该一直将恐龙骨骼显示在.txt文件中,但是我的代码指出所有骨骼都显示0次。
print('Bones found:')
f=open('bones.txt')
bones = {line.replace('\n', ''): 0 for line in f}
for bone in f:
if bone in bones:
bones[bone]=bones[bone]+1
for y in bones:
print(y+':'+str(bones[y]))
bones.txt文件为:
Ankylosaurus
Pachycephalosaurus
Ankylosaurus
Tyrannosaurus Rex
Ankylosaurus
Struthiomimus
Struthiomimus
它说:
Bones found:
Ankylosaurus:0
Pachycephalosaurus:0
Tyrannosaurus Rex:0
Struthiomimus:0
但应该说:
Bones found:
Ankylosaurus: 3
Pachycephalosaurus: 1
Tyrannosaurus Rex: 1
Struthiomimus: 2
答案 0 :(得分:2)
您只能使用一个迭代器(通过使用open(file.txt)
获得一次。以下代码应适用于您的情况。此代码使用了Counter,它包含在标准python中库,用于计数字符串的出现。
通过使用计数器
# import the Counter so it can be used
from collections import Counter
# open the text file in read mode, by using this construct,
# the lock will be released after the with-block to ensure
# resources are freed correctly
with open("bones.txt") as file:
# for every line in the file; remove the \n and insert it into the counter
counts = Counter(line.strip() for line in file)
# print every key in the counter
for dinosaur in counts:
print("{}: {}".format(dinosaur, counts[dinosaur]))
使用字典
此代码不使用计数器,但操作完全相同。
# open the text file in read mode, by using this construct,
# the lock will be released after the with-block to ensure
# resources are freed correctly
with open("bones.txt") as file:
# create a dictionary to store the counts
counts = dict()
# iterate over every line in the file
for line in file:
# remove the \n from the line
stripped = line.strip()
if stripped in counts:
# key already exists -> increment it
counts[stripped] += 1
else:
# key doesn't exist -> add it
counts[stripped] = 1
# print every key in the counts dictionary
for dinosaur in counts:
print("{}: {}".format(dinosaur, counts[dinosaur]))
输出
Pachycephalosaurus: 1
Struthiomimus: 2
Ankylosaurus: 3
Tyrannosaurus Rex: 1