请你帮我写一个计算字母字符的函数。我此代码的当前输出是这样的:
它包含5个字母字符,其中4个(80.0%)是' h'
此代码的输出应如下所示: 它包含5个字母字符,其中5(100.0%)是' h'。我想同样对待大写/小写字母
def count(p):
lows = "abcdefghijklmnopqrstuvwxyz"
ups = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numberOfh = 0
totalChars = 0
for achar in p:
if achar in lows or achar in ups:
totalChars = totalChars + 1
if achar == 'h':
numberOfh = numberOfh + 1
percent_with_h = (numberOfh / totalChars) * 100
print("It contains", totalChars, "alphabetic characters of which", numberOfh, "(", percent_with_h, "%)", "are 'h'.")
p = "Hhhhh"
count(p)
答案 0 :(得分:1)
dataStreamGenerator
我认为应该做你想做的事情
答案 1 :(得分:0)
只需将if
语句更改为
if achar == 'h' or achar == 'H':
如果你想算上所有' h'和' H'。
答案 2 :(得分:0)
如果你想计算字符串中任何字母的出现次数,而不仅仅是你可以使用这样的东西,它会返回一个字典,其中包含每个字母作为键,百分比作为值:
def count_alphas(s):
s = s.lower()
alpha_set = set(s)
alpha_counts = {}
for x in alpha_set:
alpha_counts[x] = s.count(x) / float(len(s)) * 100
return alpha_counts
# an example use:
print(count_alphas('thisissomeexampletext'))