【问题标题】:Python, check how much of a string is in uppercase?Python,检查有多少字符串是大写的?
【发布时间】:2018-11-21 16:28:01
【问题描述】:

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

带触摸屏的多弗拉明戈 lorem ipsum

我尝试使用正则表达式(在此处找到解决方案):

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

但这会找到所有大写字母,我不知道是否全部或超过 50%(包括全部)是大写的?

我只想给字母编号(所以没有数字、空格、换行等)

【问题讨论】:

    标签: python string python-3.x


    【解决方案1】:

    您可以使用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
    

    另请参阅 summap 上的文档,您可能会发现自己经常使用这些文档。此外,这使用了 bool is a subclass of int 并被适当地转换为求和的事实,这对于某些人来说可能过于隐晦。

    【讨论】:

      【解决方案2】:

      Regex 在这里似乎有点矫枉过正。您可以将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.isupper, 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
      

      【讨论】:

      • 或者你可以使用:statistics.mean(ch.isupper() for ch in s if not ch.isspace())
      • @JonClements,是的,好点,但我认为由于if 条件,有点有点混乱。
      • 好吧,既然您要逐个字符地进行迭代以进行 isupper 检查,我认为使用''.join(x.split()) 创建一个新字符串进行迭代有点麻烦:)
      • map方法不正确,应将str.upper改为str.isupper。
      • @Adam75752,改为isupper,我不明白为什么map方法在这里不起作用。
      【解决方案3】:

      适用于任何布尔函数和可迭代的通用解决方案(有关仅查看 str.isalpha() 的版本,请参见下文):

      def percentage(data, boolfunc):
          """Returns how many % of the 'data' returns 'True' for the given boolfunc."""
          return (sum(1 for x in data if boolfunc(x)) / len(data))*100
      
      text = "DOFLAMINGO WITH TOUCH SCREEN lorem ipsum"
      
      print( percentage( text, str.isupper ))
      print( percentage( text, str.islower ))
      print( percentage( text, str.isdigit ))
      print( percentage( text, lambda x: x == " " ))
      

      输出:

      62.5  # isupper
      25.0  # islower
      0.0   # isdigit
      12.5  # lambda for spaces
      

      schwobaseggl 的更好

      return sum(map(boolfunc,data)) / len(data)*100
      

      因为它不需要持久化列表,而是使用生成器。


      编辑:仅使用 str.isalpha 字符并允许多个布尔函数的第二个版本:

      def percentage2(data, *boolfuncs):
          """Returns how many % of the 'data' returns 'True' for all given boolfuncs.
      
          Only uses str.isalpha() characters and ignores all others."""
          count = sum(1 for c in data if c.isalpha())
          return sum(1 for x in data if all(f(x) for f in boolfuncs)) / count * 100
      
      text = "DOFLAMINGO WITH TOUCH SCREEN lorem ipsum"
      
      print( percentage2( text, str.isupper, str.isalpha ))
      print( percentage2( text, str.islower, str.isalpha ))
       
      

      输出:

      71.42857142857143
      28.57142857142857
      

      【讨论】:

        【解决方案4】:

        使用正则表达式,这是您可以做到的一种方式(假设s 是有问题的字符串):

        upper = re.findall(r'[A-Z]', s)
        lower = re.findall(r'[a-z]', s)
        percentage = ( len(upper) / (len(upper) + len(lower)) ) * 100
        

        它找到大写和小写字符的列表,并使用它们的长度获取百分比。

        【讨论】:

        • ( len(upper) / len(upper) + len(lower) ) == 1 + len(下)
        • @Patrick Artner,我错过了一对括号。我会编辑答案。
        【解决方案5】:

        这是一种方法:

        f = sum(map(lambda c: c.isupper(), f)) / len(f)
        (sum(map(lambda c: c.isupper(), f)) / len(f)) > .50  
        

        【讨论】:

          【解决方案6】:

          类似下面的东西应该可以工作。

          string = 'DOFLAMINGO WITH TOUCH SCREEN lorem ipsum'
          rx = re.sub('[^A-Z]', '', string)
          print(len(rx)/len(string))
          

          【讨论】:

            【解决方案7】:

            试试这个,它很短并且可以完成工作:

            text = "DOFLAMINGO WITH TOUCH SCREEN lorem ipsum"
            print("Percent in Capital Letters:", sum(1 for c in text if c.isupper())/len(text)*100)
            # Percent in Capital Letters: 62.5
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2015-02-08
              • 1970-01-01
              • 2012-01-03
              • 2014-08-13
              • 2017-12-24
              • 2010-12-16
              • 2014-06-23
              相关资源
              最近更新 更多