我是一个初学者的Python程序员,正在尝试制作一个可以计算文本文件中字母数量的程序。以下是我的代码:
import string
text = open('text.txt')
letters = string.ascii_lowercase
for i in text:
text_lower = i.lower()
text_nospace = text_lower.replace(" ", "")
text_nopunctuation = text_nospace.strip(string.punctuation)
for a in letters:
if a in text_nopunctuation:
num = text_nopunctuation.count(a)
print(a, num)
如果文本文件包含
hello bob
,我希望输出为:b 2
e 1
h 1
l 2
o 2
我的问题是,当文本文件包含多行文本或包含标点符号时,它不能正常工作。