开发者

python - Letter Frequency [closed]

开发者 https://www.devze.com 2023-02-23 13:40 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.

Write a Python function called hist() which takes a string as an argument, and creates a visual representation of the frequency of its alphabetic letters by printing each letter in uppercase the number of times it appears in the string, with each letter on a separate line, grouped from mo开发者_高级运维st to least.


A MUCH simpler approach is:

import string
def hist(s):
    d = {}
    for i in s.upper():
        if i.isalpha():
            d[i] = d[i] + 1 if i in d else 1
    for k in sorted(d.keys()):
        print k*d[k]


Your code is similar, you don't need to read the file.

def hist(inputstr):
    lowlet = inputstr.upper()
    alphas = 'abcdefghijklmnopqrstuvwxyz'.upper()
    occurrences = dict( (letter, 0) for letter in alphas)
    total = 0
    for letter in lowlet:
        if letter in occurrences:
            total += 1
            occurrences[letter] += 1
    letcount = sorted(occurrences.iteritems(),key = lambda x:-x[1])
    for letter, count in letcount:
        if count>0:
             print letter*count
0

精彩评论

暂无评论...
验证码 换一张
取 消