Python,检查字符串的大小是多少?

use*_*631 2 python string python-3.x

我有一个文本,我想知道是否所有或大于50%的百分比都是大写的.

DOFLAMINGO与触摸屏lorem ipsum

我尝试使用正则表达式(在这里找到一个解决方案):

rx = re.compile(r"^([A-Z ':]+$)", re.M)
upp = rx.findall(string)
Run Code Online (Sandbox Code Playgroud)

但这找到所有上限,我不知道是否所有或超过50%(包括所有)是大写的?

我想只编号字母(所以没有数字,空格,新行等)

sch*_*ggl 6

您可以使用filterstr.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
Run Code Online (Sandbox Code Playgroud)

另请参阅文档sum以及map您可能会发现自己经常使用的文档.此外,这使用了一个事实,它bool是一个子类,int并且被适当地转换为总和,这可能对于某些人的品味而言过于隐含.


jpp*_*jpp 5

正则表达式在这里似乎太过分了。您可以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)
Run Code Online (Sandbox Code Playgroud)

或者在功能上通过map

x_upper = sum(map(str.isupper, x_chars)) > (len(x_chars) / 2)
Run Code Online (Sandbox Code Playgroud)

或者,通过statistics.mean

from statistics import mean

x_upper = mean(i.isupper() for i in s if not i.isspace()) > 0.5
Run Code Online (Sandbox Code Playgroud)

  • 或者你可以使用: `statistics.mean(ch.isupper() for ch in s if not ch.isspace())` (2认同)