现有一篇英文小说(Walden.txt文件),需要统计该小说中用到的字符的出现次数。。
以字典形式输出结果
# 打开并读取文件
with open('Walden.txt', 'r') as file:
text = file.read()
# 去除文件中的非字母符号并将所有文本转换为小写
text = ''.join([c for c in text if c.isalpha() or c.isspace()]).lower()
# 建立一个空字典来统计字符出现次数
char_count = {}
# 迭代文本中的每个字符,更新字典中的计数
for char in text:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
# 输出每个字符及其出现次数
for char in char_count:
print(char, char_count[char]