如何计算文件中的字符并按字母数字顺序打印
(如果标题更好,请进行编辑,我无法正确解释!:)这是我的代码:
with open('cipher.txt') as f:
f = f.read().replace(' ', '')
new = []
let = []
for i in f:
let.append(i)
if i.count(i) > 1:
i.count(i) == 1
else:
new = sorted([i + ' ' + str(f.count(i)) for i in f])
for o in new:
print(o)
这是cipher.txt
:
xli uymgo fvsar jsb
我应该打印出使用过的字母以及使用了多少次,我的代码可以正常工作,但是我需要按字母顺序排列,我尝试将它们放在列表中list(a)
然后进行排序,但是我不太明白想法?提前致谢!
-
每当进行计数时,您都可以
collections.Counter
在这里使用:>>> from collections import Counter >>> print sorted(Counter('xli uymgo fvsar jsb'.replace(' ', '')).most_common()) [('a', 1), ('b', 1), ('f', 1), ('g', 1), ('i', 1), ('j', 1), ('l', 1), ('m', 1), ('o', 1), ('r', 1), ('s', 2), ('u', 1), ('v', 1), ('x', 1), ('y', 1)]
如果您无法导入任何模块,则可以追加
a
到列表中然后对其进行排序:new = [] for i in f: new.append(i + ' ' + str(f.count(i)) # Note that i is a string, so str() is unnecessary
或者,使用列表推导:
new = [i + ' ' + str(f.count(i)) for i in f]
最后,要对其进行排序,只需将
sorted()
其放在周围即可。不需要额外的参数,因为您的结果是按字母顺序排列的:)。