gpt4 book ai didi

python - 计算文件中字母的频率并写入输出文件python

转载 作者:太空宇宙 更新时间:2023-11-03 15:18:49 25 4
gpt4 key购买 nike

我正在编写一个函数,它接受一个 in_file 并检查该文件中字母的频率,并以这种格式(字母:频率)写入 out_file。这是我到目前为止得到的任何人都可以帮忙吗?

def count_letters(in_file,out_file):
in_file = open(in_file,"r")
out_file = open(out_file,"w")
for line in in_file:
words = line.split()
for word in words:
for letter in word:
print(letter,':',line.count(letter),file=out_file,end="\n")

最佳答案

根本不需要分词;直接将字符串传递给计数器会更新每个字符的计数。您还需要首先收集所有计数,然后才将它们写入输出文件:

from collections import Counter

def count_letters(in_filename, out_filename):
counts = Counter()
with open(in_filename, "r") as in_file:
for chunk in iter(lambda: in_file.read(8196), ''):
counts.update(chunk)
with open(out_filename, "w") as out_file:
for letter, count in counts.iteritems():
out_file.write('{}:{}\n'.format(letter, count)

请注意,输入文件是按 8kb block 处理的,而不是一次处理;您可以调整 block 大小(最好是 2 的幂)以最大化吞吐量。

如果您希望输出文件按频率(降序)排序,您可以在此处使用 .most_common() 而不是 .iteritems()

关于python - 计算文件中字母的频率并写入输出文件python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18165075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com