如何计算文件中的字符并按字母数字顺序打印它们

时间:2013-09-02 08:03:13

标签: python sorting python-3.x counter

(如果你有一个更好的标题,做编辑,我无法正确解释!:) 所以这是我的代码:

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)然后对它们进行排序,但是我没有得到它,任何想法?提前谢谢!

2 个答案:

答案 0 :(得分:3)

每当处理计数时,您可以在此使用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()放在它周围即可。不需要额外的参数,因为您的结果是按字母顺序排列的:)。

答案 1 :(得分:0)

这是一个没有导入的oneliner:

{s[i]: n for i, n in enumerate(map(s.count, s))}

按字母顺序排列(如果上面是d):

for k in sorted(d): print k, d[k]

或其他版本(oneliner alphabetical):

sorted(set([(s[i], n) for i, n in enumerate(map(s.count, s))]))

相关问题