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條經驗 獲得超8個贊
使用正則表達式,這是您可以做到的一種方式(假設這s是有問題的字符串):
upper = re.findall(r'[A-Z]', s)
lower = re.findall(r'[a-z]', s)
percentage = ( len(upper) / (len(upper) + len(lower)) ) * 100
它找到大寫和小寫字符的列表,并使用它們的長度獲取百分比。
添加回答
舉報