计数所有字母的频率数

2024-03-29 10:44:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着数一数每个字母的频率

这是我的主要文件:

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)

我不知道为什么我没有得到整本字典,而只有第一行


Tags: 文件textinfromimportoutputdataget
2条回答

是的,或者您可以使用collections Counter

from collections import Counter

frequencies = Counter(text)

对于打印,您必须按排序顺序遍历键:

def print_output(frequencies):
     for key in sorted(frequencies.keys()):
         print(key, frequencies[key])

你这样编字典

    if ch in ascii_lowercase:
        if ch not in data:
            data[ch] = 1
        else:
            data[ch] += 1  

所以我假设键是字符,值是字符的计数:

{'a':867, 'b':233, ....}

^{}以元组的形式生成(键,值)对,就像('a', 867)。你知道吗

def print_output(data):
    for char in sorted(data.items()):
        #print(char)
        print(str(char), str(data[char]))

所以for char in sorted(data.items()):中的char是('a',867),您试图将它用作导致KeyErrorstr(data[char])键。你知道吗

试试看

def print_output(data):
     for char, count in sorted(data.items()):
         print(str(char), str(count))

或者

def print_output(data):
     for char in sorted(data):
         print(str(char), str(data[char]))

相关问题 更多 >