如何计算文件中的字符并按字母数字顺序打印 [英] How to count characters in a file and print them sorted alphanumerically

查看:75
本文介绍了如何计算文件中的字符并按字母数字顺序打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(如果标题更好,请进行编辑,我无法正确解释!:) 这是我的代码:

(If you have a better title, do edit, I couldn't explain it properly! :) So this is my code:

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)中,然后对它们进行排序,但是我没有不太明白,有什么想法吗?预先感谢!

I'm supposed to print out the letters used and how many times they are used, my code works, but I need it alphabetical, I tried putting them in a list list(a) and then sorting them, but i didn't quite get it, any ideas? Thanks in advance!

推荐答案

每当处理计数时,都可以使用 collections.Counter 此处:

Whenever dealing with counting, you can use collections.Counter here:

>>> 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附加到列表中,然后对其进行排序:


If you can't import any modules, then you can append a to a list and then sort it:

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()放在其周围.不需要额外的参数,因为您的结果是按字母顺序排列的:).

Finally, to sort it, just put sorted() around it. No extra parameters are needed because your outcome is alphabetical :).

这篇关于如何计算文件中的字符并按字母数字顺序打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆