我有一個練習來查找字串中最常見的字母,不包括標點符號、數字和空格,結果應該是小寫的“A”==“a”。
是)我有的:
import string
def most_common_letter(text: str):
s = string.ascii_lowercase
text = text.lower()
counter = {}
for i in text:
if i in s:
counter[i] = 1
for k,v in counter.items():
if k == i:
v = 1
return counter
但結果我的字典不算數。錯在哪里?
uj5u.com熱心網友回復:
你永遠不會增加counter. 您只需將計數設定為1角色在s. 遞增的回圈v對字典沒有影響。
您可以使用defaultdict(int)創建一個字典,0在您第一次訪問它們時自動初始化元素。
填寫字典后,可以得到最大計數,然后找到所有具有該計數的字母。
import string
from collections import default dict
def most_common_letter(text: str):
s = string.ascii_lowercase
text = text.lower()
counter = defaultdict(int)
for i in text:
if i in s:
counter[i] = 1
highest = max(counter.values())
return [k for k, v in counter.items() if v == highest]
uj5u.com熱心網友回復:
試試這個:
from string import ascii_lowercase
def most_common_letter(text: str):
counter = {}
for letter in text.lower():
if letter not in counter:
counter[letter] = 0
if letter in ascii_lowercase:
counter[letter] = 1
return max(counter, key=counter.get)
此解決方案在確保該鍵存在于字典中后遞增該值,然后回傳具有最大值的鍵。
uj5u.com熱心網友回復:
第一個小寫字串
s = "Ascsdfavsdfsdassdf!@5DFA7&".lower()
接下來,只保留字母字符
s_alpha = filter(lambda x:x.isalpha(), s)
最后,用于Counter計算重復字符并保留最常見的字符。
from collections import Counter
most_char = Counter(s_alpha).most_common(1)
print(most_char)
# output: [('s', 6)]
注意: most_char[0][0]列印的字符
您可以讀取函式中的所有行并運行它
def most_common_letter(text: str) -> str:
text_lowercase: str = text.lower()
text_alpha: str = filter(lambda x:x.isalpha(), text_lowercase)
most_char: List[tuple] = Counter(text_alpha).most_common(1)
return most_char[0][0]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/470746.html
