Python 计算文件中字符串的出现次数
我的代码应该统计在.txt文件中显示恐龙骨骼的所有时间,但我的代码指出所有骨骼显示0次Python 计算文件中字符串的出现次数,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我的代码应该统计在.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])) bo
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
您只能使用迭代器(通过使用
open(file.txt)
获得)。以下代码应适用于您的情况。此代码使用了标准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
我是初学者。这是我的第四周。你已经用完了你的文件迭代器,你不能在文件上循环多次。@MitchelPaulin这很好,在这种情况下,因为他们在一个
dict
上循环。也在文件上重复两次:一次在dict理解中,第二次在for
@biwwibourdi中我更新了我的答案也包括一个非反驳性的回答