我需要一个函数来计算每个字母出现在字符串中的次数。它必须将大写字母和小写字母统计为相同的字母。我有点做了,但它并不完全漂亮。
def lmao(x):
aye=x.count("a")
Aye=x.count("A")
bye=x.count("b")
Bye=x.count("B")
cye=x.count("c")
Cye=x.count("C")
dye=x.count("d")
Dye=x.count("D")
Eye=x.count("E")
eye=x.count("e")
Fye=x.count("F")
fye=x.count("f")
Gye=x.count("G")
gye=x.count("g")
Hye=x.count("H")
hye=x.count("h")
Iye=x.count("I")
iye=x.count("i")
Jye=x.count("J")
jye=x.count("j")
Kye=x.count("K")
kye=x.count("k")
Lye=x.count("L")
lye=x.count("l")
Mye=x.count("M")
mye=x.count("m")
Nye=x.count("N")
nye=x.count("n")
Oye=x.count("O")
oye=x.count("o")
Pye=x.count("P")
pye=x.count("P")
Qye=x.count("Q")
qye=x.count("q")
rye=x.count("r")
Rye=x.count("R")
sye=x.count("s")
Sye=x.count("S")
tye=x.count("t")
Tye=x.count("T")
uye=x.count("u")
Uye=x.count("U")
Vye=x.count("V")
vye=x.count("v")
Wye=x.count("W")
wye=x.count("w")
Xye=x.count("X")
xye=x.count("x")
Yye=x.count("Y")
yye=x.count("y")
Zye=x.count("Z")
zye=x.count("z")
killme=(aye+Aye,bye+Bye,cye+Cye,Dye+dye,Eye+eye,Fye+fye,Gye+gye,Hye+hye,Iye+iye,jye+Jye,Kye+kye,Lye+lye,Mye+mye,Nye+nye,Oye+oye,Pye+pye,Qye+qye,rye+Rye,sye+Sye,Tye+tye,uye+Uye,Vye+vye,Wye+wye,xye+Xye,Yye+yye,Zye+zye)
return killme
所以是的,那就是我想出的灾难。有没有办法缩短这个过程?
答案 0 :(得分:5)
使用UIImageView
https://docs.python.org/2/library/collections.html#counter-objects
collections.Counter
会给你所有出现的每个字母,忽略大小写
答案 1 :(得分:2)
准确回复您的要求:
import string
def lmao(x):
return tuple(x.lower().count(c) for c in string.lowercase)
答案 2 :(得分:0)
这可能有所帮助:
def counter(text):
count_list = []
for char in "abcdefghijklmnopqrstuvwxyz":
count_list.append(text.lower().count(char))
return tuple(count_list)
print(counter("Helllo123"))
输出:
(0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 3, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
答案 3 :(得分:0)
将计数器与字典理解结合使用,以获得每个字母的计数。
import string
from collections import Counter
对于alpha排序的元组,
def count_letter_tuples(sentence):
return tuple(Counter(sentence.lower()).get(c, 0) for c in string.ascii_lowercase)
>>> count_letter_tuples("Some Big Sentence")
(0, 0, 1, 0, 4, 0, 1, 0, 1, 0, 0, 0, 1, 2, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0)
或者是字典回复:
def count_letters(sentence):
return {c: Counter(sentence.lower()).get(c, 0) for c in string.ascii_lowercase}
>>> count_letters("Some Big Sentence")
{'a': 0,
'b': 1,
'c': 1,
'd': 0,
'e': 4,
'f': 0,
'g': 1,
'h': 0,
'i': 1,
'j': 0,
'k': 0,
'l': 0,
'm': 1,
'n': 2,
'o': 1,
'p': 0,
'q': 0,
'r': 0,
's': 2,
't': 1,
'u': 0,
'v': 0,
'w': 0,
'x': 0,
'y': 0,
'z': 0}