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

Python 3.x Python 3,计算文件中的字母频率,python-3.x,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

该行: 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)
#编写一个程序,读取文件并按顺序打印字母
#频率顺序。您的程序应将所有输入转换为低位
#大小写,只计算字母a-z。你的程序不应该算数
#空格、数字、标点符号或字母a-z以外的任何符号。
导入字符串
从字符串导入数字
fname=输入(“输入文件:”)
如果len(fname)<1:fname=“romeo full.txt”
fhand=打开(fname)
charcount=dict()
对于fhand中的线路:
line=line.rstrip()
line=line.lower()
line=line.translate(str.maketrans(“”,,,string.标点))
line=str.maketrans(“,”,位)
对于行中的单词:
对于word中的字符:
charcount[char]=charcount.get(char,0)+1
打印(字符数)

打印出
。它们是什么类型的?阅读文档以查看
str.maketrans
返回的内容。我认为您希望使用
line=line.translate(str.maketrans(“”,,,digits))
而忘记键入
line。translate
在旁注中,一定要查看
集合
模块中的
计数器。而且
list(somestring)
somestring
转换为字符列表。因此,你可以在一行中完成任务。我认为你使翻译变得比必要的更复杂。下面是我要做的几件事:1:对文件I/o使用上下文管理器(例如,
将open(fname)设为f
),2:逐行读取文件内容,3:迭代每行中的字符,4:忽略c.lower()不在[a-z]中的所有内容,增加dict中的计数器[c.lower()]。