我正在尝试在'words.txt'文件中打印所有字母的计数和小数频率,不包括\ n字符。我已经编写了以下代码段
FILENAME = 'words.txt'
fvar = open(FILENAME, 'r') # open file for reading
bigline = fvar.read() # read ENTIRE file into single string
print("Number of characters is: %d" % len(bigline))
length_without_newlines = len(bigline) - bigline.count('\n')
ref_string = 'abcdefghijklmnopqrstuvwxyz'
num_l = 0
for x in bigline:
if x in ref_string:
num_l += 1
print('Count of letter',x, 'is: ', num_l)
frac_freq = float(num_l)/float(length_without_newlines)
#This isn't working properly
是否可以遍历ref_string并打印每个字母的计数和小数频率(换行符除外);也就是说,将特定字母的计数除以文件中字母的总数,而不计算换行符?由于我是python的新手,所以如果有人可以更新此函数的代码,那就太好了。
答案 0 :(得分:1)
希望此示例有所帮助:
from collections import Counter
counter = Counter('line')
total = sum(counter.values())
for letter, count in counter.items():
print(f'Count of letter {letter} is: {count}')
frac_freq = float(count)/float(total)