计算文本中字母的频率fi

2024-04-29 04:55:22 发布

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

在python中,如何遍历文本文件并计算每个字母的出现次数?我知道我可以使用一个'for x-in-file'语句来完成它,然后设置26个左右的if-elif语句,但肯定有更好的方法来完成它?

谢谢。


Tags: 方法inforif字母语句次数file
2条回答

使用collections.Counter()

from collections import Counter
with open(file) as f:
    c = Counter()
    for x in f:
        c += Counter(x.strip())

正如@mgilson所指出的,如果文件不是那么大,您可以简单地执行以下操作:

c = Counter(f.read().strip())

示例:

>>> c = Counter()
>>> c += Counter('aaabbbcccddd eee fff ggg')
>>> c
Counter({'a': 3, ' ': 3, 'c': 3, 'b': 3, 'e': 3, 'd': 3, 'g': 3, 'f': 3})
>>> c += Counter('aaabbbccc')
Counter({'a': 6, 'c': 6, 'b': 6, ' ': 3, 'e': 3, 'd': 3, 'g': 3, 'f': 3})

或者使用字符串的count()方法:

from string import ascii_lowercase     # ascii_lowercase =='abcdefghijklmnopqrstuvwxyz'
with open(file) as f:
    text = f.read().strip()
    dic = {}
    for x in ascii_lowercase:
        dic[x] = text.count(x)

基本上,没有进口: 字母是决定某事物是否为字母的函数, 这样你就可以数除一般英文字母以外的其他东西了

def add_or_init(dictionary, c):
        if(c in dictionary):
                dictionary[c]+=1
        else:
                dictionary[c]=1
def count_one_letter(dictionary, c, is_letter):
        if is_letter(c):
                add_or_init(dictionary, c)
def count_letters(dictionary, string, is_letter):
        for c in string:
                count_one_letter(dictionary, c, is_letter)
        return dictionary

#count all characters
count_letters(dict(),'aaabbbcccddd eee fff ggg',lambda x: True)
# => {'a': 3, ' ': 3, 'c': 3, 'b': 3, 'e': 3, 'd': 3, 'g': 3, 'f': 3}

相关问题 更多 >