我是一个初级的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
我的问题是,当文本文件包含多行文本或有标点符号时,它不能正常工作。
使用re:
它是更优雅和干净的柜台,尽管如此。
这是使用Counter完成所需任务的非常可读的方法:
您可以迭代得到的dict,以您想要的格式打印它。
你必须使用
collections.Counter
它打印:
您的
text
变量应该是:为了获得所需的输出:
在我的示例中,它打印:
有关详细信息Counters doc
相关问题 更多 >
编程相关推荐