Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

python - How to count characters in a file and print them sorted alphanumerically

(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)

And this is cipher.txt:

xli uymgo fvsar jsb

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)]

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

Or, using a list comprehension:

new = [i + ' ' + str(f.count(i)) for i in f]

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...