首页 > 解决方案 > 计算txt文件中的字母

问题描述

您好,我正在尝试编写一个可以计算 txt 文件中字母的代码。

我写了一个代码,但它只计算小写字母。我曾尝试使用较低的功能,但没有运气

import numpy as np

def letterFrequency(filename):
    letters="abcdefghijklmnopqrstuvwxyz"

    filein = open(filename, "r")
    lines = filein.readlines()
    smalltxt = "".join(lines)
    totalOccurrences=0
    v=[]

    for i in letters:
        occurrences=smalltxt.count(i)
        totalOccurrences=totalOccurrences + occurrences
        v.append(occurrences)

    v=np.array([v])
    freq=(v/totalOccurrences)*100

    return  freq

print(letterFrequency("small_text.txt"))

a 百分比的输出为 7.74%,但预期输出应为 8.1%。我相信它是因为它只计算小写字母

标签: pythonspyder

解决方案


如果你想用不区分大小写的方案来计算字母,只需将它们全部转换为单个大小写。修正线。

smalltxt = "".join(lines).lower()

应该做的工作。


推荐阅读