3 回答

TA贡献1848条经验 获得超2个赞
您可以使用filter和str.isalpha清除非字母字符并str.isupper计算大写字符并计算比率:
s = 'DOFLAMINGO WITH TOUCH SCREEN lorem ipsum'
alph = list(filter(str.isalpha, s)) # ['D', ..., 'O', 'W', ..., 'N', 'l', 'o', ...]
sum(map(str.isupper, alph)) / len(alph)
# 0.7142857142857143
另请参见上的文档sum和map您可能经常使用发现自己。此外,这使用了bool作为 的子类int的事实,并且为求和进行了适当的转换,这对于某些人来说可能过于隐含。

TA贡献1744条经验 获得超4个赞
正则表达式在这里似乎有点矫枉过正。您可以使用sum生成器表达式:
x = 'DOFLAMINGO WITH TOUCH SCREEN lorem ipsum'
x_chars = ''.join(x.split()) # remove all whitespace
x_upper = sum(i.isupper() for i in x_chars) > (len(x_chars) / 2)
或功能上通过map:
x_upper = sum(map(str.upper, x_chars)) > (len(x_chars) / 2)
或者,通过statistics.mean:
from statistics import mean
x_upper = mean(i.isupper() for i in s if not i.isspace()) > 0.5

TA贡献2039条经验 获得超7个赞
使用正则表达式,这是您可以做到的一种方式(假设这s是有问题的字符串):
upper = re.findall(r'[A-Z]', s)
lower = re.findall(r'[a-z]', s)
percentage = ( len(upper) / (len(upper) + len(lower)) ) * 100
它找到大写和小写字符的列表,并使用它们的长度获取百分比。
添加回答
举报