Python从文本Fi创建字母计数

2024-10-03 21:26:25 发布

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

我只想从一个文本文件中数一数字母。我想排除任何标点和空格。这是我目前掌握的情况。我一直在寻找这样做的方法,但每当我试图排除某些字符时,总是会出现错误。非常感谢您的帮助。你知道吗

#Read Text Files To Memory
with open("encryptedA.txt") as A:
    AText = A.read()
with open("encryptedB.txt") as B:
    BText = B.read()

#Create Dictionary Object
from collections import Counter
CountA = Counter(AText)
print(CountA)
CountB = Counter(BText)
print(CountB)

Tags: txtreadaswith字母counteropen空格
1条回答
网友
1楼 · 发布于 2024-10-03 21:26:25

您的思路是正确的,但是您希望根据字母(使用isalpha())或字母数字(使用isalnum())的字符筛选文本文件:

from collections import Counter
with open('data.txt') as f:
    print (Counter(c for c in f.read() if c.isalpha())) # or c.isalnum()

对于我的示例文件,这个打印:

Counter({'t': 3, 'o': 3, 'r': 3, 'y': 2, 's': 2, 'h': 2, 'p': 2, 'a': 2, 'g': 1, 'G': 1, 'H': 1, 'i': 1, 'e': 1, 'M': 1, 'S': 1})

相关问题 更多 >