我正在創建一個函式,該函式回傳一個直方圖,其中包含字母表中的每個字母和星號,用于標出每個字符在字串中出現的次數。到目前為止,我有:
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!' 的正確輸出 將是:

如何更改我的代碼以使直方圖按預期作業(按順序排列所有字母,在每個字母旁邊顯示一個星號表示其字符頻率,當字母不在文本中時仍顯示字母,只是沒有星號。 )
uj5u.com熱心網友回復:
迭代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.
uj5u.com熱心網友回復:
您可以使用 acollections.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
一些檔案:
Counterstring.ascii_lowercase
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315514.html
上一篇:處理Euler專案問題的Python代碼時出現記憶體錯誤
下一篇:ReactNative[TypeError:undefinedisnotanobject(evaluating'iter[Symbol.iterator]')]錯誤
