我试着数一数每个字母的频率
这是我的主要文件:
from moduleA import get_text, process_data,print_output
import os
filename1 = os.path.join(os.getcwd(),'script01.txt')
filename2 = os.path.join(os.getcwd(),'script02.txt')
myList1 = get_text(filename1)
myList2 = get_text(filename2)
data01=process_data(myList1)
data02=process_data(myList2)
print_output(data01)
print_output(data02)
以下是moduleA文件:
def get_text(file_name):
text = None
try:
with open(file_name) as f:
text = f.read()
except IOError as io:
print(str(io))
return text
def process_data(text_data):
from string import ascii_lowercase
data = {}
for char in text_data:
ch = char.lower()
if ch in ascii_lowercase:
if ch not in data:
data[ch] = 1
else:
data[ch] += 1
return(data)
def print_output(data):
for char in sorted(data.items()):
print(str(char), str(data[char]))
这是我得到的错误:
print(str(char), str(data[char]))
KeyError: ('a', 867)
我不知道为什么我没有得到整本字典,而只有第一行
是的,或者您可以使用
collections Counter
:对于打印,您必须按排序顺序遍历键:
你这样编字典
所以我假设键是字符,值是字符的计数:
^{} 以元组的形式生成(键,值)对,就像
('a', 867)
。你知道吗所以
for char in sorted(data.items()):
中的char
是('a',867),您试图将它用作导致KeyError的str(data[char])
键。你知道吗试试看
或者
相关问题 更多 >
编程相关推荐