Python 3,计算文件中的字母频率

时间:2019-12-05 01:50:09

标签: python-3.x

该行: for Char in word返回错误“ TypeError:'int'对象不可迭代” 它如何变成整数而不是字符串? 我该如何迭代呢?

# Write a program that reads a file and prints the letters in decreasing
# order of frequency. Your program should convert all the input to lower
# case and only count the letters a-z. Your program should not count
# spaces, digits, punctuation, or anything other than the letters a-z.

import string
from string import digits

fname = input("Enter file:")
if len(fname) < 1 : fname = "romeo-full.txt"
fhand = open(fname)

charcount = dict()

for line in fhand:
    line = line.rstrip()
    line = line.lower()
    line = line.translate(str.maketrans('','',string.punctuation))
    line = str.maketrans("", "", digits)

    for word in line:
        for char in word:
            charcount[char] = charcount.get(char, 0) + 1

print(charcount)

0 个答案:

没有答案