我需要介绍文本中出现的字母.如果没有出现字母之一,则应显示零,并且输出应按字母顺序排序.我已经准备了以下Python代码,我的问题是如何显示非出现字母的零,如何基于列表键对列表值进行排序以对输出进行排序?
fdist = Counter(c for c in f.lower() if c.isalpha())
print sorted(fdist.items()) #only to show the output details
print fdist.values()
示例文本的输出如下所示:
[('a', 46), ('b', 5), ('c', 11), ('d', 22), ('e', 76), ('f', 13), ('g', 7), ('h', 29), ('i', 30), ('j', 1), ('k', 6), ('l', 21), ('m', 11), ('n', 34), ('o', 31), ('p', 6), ('q', 1), ('r', 24), ('s', 32), ('t', 52), ('u', 7), ('v', 2), ('w', 10), ('y', 11)]
[46, 11, 5, 76, 22, 7, 13, 30, 29, 6, 1, 11, 21, 31, 34, 1, 6, 32, 24, 7, 52, 10, 2, 11]
但输出应如下所示:
[46, 5, 11, 22, 76, 13, 7, 29, 46, 1, 6, 21, 11, 34, 31, 6, 1, 24, 32, 52, 7, 2, 10, 0, 11, 0]
解决方法:
像这样的东西(暂时忽略排序部分)?
import string
result = [fdist.get(l, 0) for l in string.letters]
要么
result = [fdist.get(l, 0) for l in string.ascii_lowercase]
因为您只处理小写字符