创建直方图以映射字符频率

Creating a histogram to map character frequency

我正在创建一个函数,该函数 returns 一个包含字母表中每个字母和星号的直方图,标出每个字符在字符串中出现的次数。到目前为止我有:

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

def character_frequency_string(text):
    #remove_extraneous function removes anything that is not a letter in the alphabet from the text string
    new_text = remove_extraneous(text)
    
    for char in new_text:
        if char in new_text:
            print(char +' ' + '*'*new_text.count(char))
        if char not in new_text:
            print(char)

我的文档字符串如下(输出与现在一样,不正确):

'''
    Examples:
    >>> character_frequency_string('hello world!')
    h *
    e *
    l ***
    l ***
    o **
    w *
    o **
    r *
    l ***
    d *
    >>> character_frequency_string('testing!')
    t **
    e *
    s *
    t **
    i *
    n *
    g *
    '''

'hello world!' 的正确输出是:

我怎样才能更改我的代码以使直方图按预期工作(所有字母顺序排列,在每个字母旁边显示一个星号表示其字符频率,当字母不在文本中时仍显示字母,只是没有星号。)

遍历 alphabet:

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
            'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']


def character_frequency_string(text):
    new_text = text
    for char in alphabet:
        print(char + ' ' + '*' * new_text.count(char))


character_frequency_string('hello world!')

输出

a 
b 
c 
d *
e *
f 
g 
h *
i 
j 
k 
l ***
m 
n 
o **
p 
q 
r *
s 
t 
u 
v 
w *
x 
y 
z 

上述解决方案具有 O(n^2) 时间复杂度,更高效的替代方案是使用 collections.Counter.

您可以使用 collections.Counter 和 f 字符串执行以下操作:

from collections import Counter
from string import ascii_lowercase as alphabet

def character_frequency_string(text):
    c = Counter(text.lower())
    for x in alphabet:
        print(f"{x} {'*' * c[x]}")

>>> character_frequency_string("hello world!")
a 
b 
c 
d *
e *
f 
g 
h *
i 
j 
k 
l ***
m 
n 
o **
p 
q 
r *
s 
t 
u 
v 
w *
x 
y 
z 

部分文档: