python - 计算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%。我相信它是因为它只计算小写字母
解决方案
如果你想用不区分大小写的方案来计算字母,只需将它们全部转换为单个大小写。修正线。
smalltxt = "".join(lines).lower()
应该做的工作。
推荐阅读
- python - Numpy 数组所有和任何操作与 3d 数组中的组合
- javascript - 纯javascript折叠导航栏
- reactjs - 将 create-react-app 项目传输到 Webpack 并且没有错误,但永远不会调用 index.js
- swift - UITextField 在不是时被视为 nil
- javascript - 如何在javascript中用数组中的索引替换键
- javascript - 如何识别数组中的最大数字,但如果两个或更多数字被绑定为最大数字,则无法识别?
- python - 熊猫中的自定义 Grouper 对象
- python - 将行分成偶数组并给出新的组名
- java - 有没有办法让IDEA在多行时不对齐方法?
- python - Django 模板在当前 URL 后添加 GET 参数