【问题标题】:Count spaces in text (treat consecutive spaces as one)计算文本中的空格(将连续空格视为一个)
【发布时间】:2016-07-31 14:29:24
【问题描述】:

如何计算文本中空格或换行符的数量,以使连续的空格仅计为一个? 例如,这非常接近我想要的:

string = "This is an  example text.\n   But would be good if it worked."
counter = 0
for i in string:
    if i == ' ' or i == '\n':
        counter += 1
print(counter)

但是,返回的结果不是15,而是应该只有11

【问题讨论】:

    标签: python python-3.x spaces


    【解决方案1】:

    默认的str.split() 函数会将连续的空格视为一个。所以简单地拆分字符串,得到结果列表的大小,然后减一。

    len(string.split())-1

    【讨论】:

    • 这是一个聪明的解决方案,但牺牲了代码的清晰度。
    • 这对于string = "This is an example text.\n But would be good if it worked. "或任何以空格结尾的行都失败,正确答案是12,你需要len(string.split()) - (not string[-1].isspace())
    【解决方案2】:

    假设您被允许使用 Python 正则表达式;

    import re
    print len(re.findall(ur"[ \n]+", string))
    

    快速简单!

    更新:此外,使用 [\s] 而不是 [ \n] 来匹配任何空白字符。

    【讨论】:

      【解决方案3】:

      你可以这样做:

      string = "This is an  example text.\n   But would be good if it worked."
      counter = 0
      # A boolean flag indicating whether the previous character was a space
      previous = False 
      for i in string:
          if i == ' ' or i == '\n': 
              # The current character is a space
              previous = True # Setup for the next iteration
          else:
              # The current character is not a space, check if the previous one was
              if previous:
                  counter += 1
      
              previous = False
      print(counter)
      

      【讨论】:

        【解决方案4】:

        rerescue。

        >>> import re
        >>> string = "This is an  example text.\n   But would be good if it worked."
        >>> spaces = sum(1 for match in re.finditer('\s+', string))
        >>> spaces
        11
        

        这消耗最少的内存,构建临时列表的替代解决方案是

        >>> len(re.findall('\s+', string))
        11
        

        如果您只想考虑空格字符和换行符(例如,与制表符相反),请使用正则表达式 '(\n| )+' 而不是 '\s+'

        【讨论】:

        • 这会处理换行符吗?
        • @th3an0maly 是的。
        【解决方案5】:

        只需存储最后一个找到的字符即可。每次循环时将其设置为 i。然后在您的内部 if 中,如果找到的最后一个字符也是空白字符,则不要增加计数器。

        【讨论】:

          【解决方案6】:

          您可以遍历数字以将它们用作索引。

          for i in range(1, len(string)):
              if string[i] in ' \n' and string[i-1] not in ' \n':
                  counter += 1
          if string[0] in ' \n':
              counter += 1
          print(counter)
          

          注意第一个符号,因为此构造从第二个符号开始,以防止IndexError

          【讨论】:

          • 索引到字符串[-1] 可能不是最好的主意
          • 这个结果也是15,而不仅仅是11。
          • 对不起,我搞砸了索引。 and 之后的部分应该被索引为i-1,而不是-1
          【解决方案7】:

          你可以使用枚举,检查下一个字符也不是空格,所以连续的空格只会算作1:

          string = "This is an  example text.\n   But would be good if it worked."
          
          print(sum(ch.isspace() and not string[i:i+1].isspace() for i, ch in enumerate(string, 1)))
          

          您还可以将iter 与生成器函数一起使用,跟踪最后一个字符并进行比较:

          def con(s):
              it = iter(s)
              prev = next(it)
              for ele in it:
                  yield prev.isspace() and not ele.isspace()
                  prev = ele
              yield ele.isspace()
          
          print(sum(con(string)))
          

          一个 itertools 版本:

          string = "This is an  example text.\n     But would be good if it worked.  "
          
          from itertools import tee, izip_longest
          
          a, b = tee(string)
          next(b)
          print(sum(a.isspace() and not b.isspace() for a,b in izip_longest(a,b, fillvalue="") ))
          

          【讨论】:

            【解决方案8】:

            试试:

            def word_count(my_string):     
                word_count = 1
                for i in range(1, len(my_string)):
                    if my_string[i] == " ":
            
                        if not my_string[i - 1] == " ":    
                            word_count += 1
            
                     return word_count
            

            【讨论】:

            • 请格式化您的代码(也使函数定义格式化)并提供一些关于您的解决方案和结果的文字(在一些示例数据上)。
            【解决方案9】:

            您可以使用函数groupby() 查找连续空格组:

            from collections import Counter
            from itertools import groupby
            
            s = 'This is an  example text.\n   But would be good if it worked.'
            
            c = Counter(k for k, _ in groupby(s, key=lambda x: ' ' if x == '\n' else x))
            print(c[' '])
            # 11
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2019-05-08
              • 1970-01-01
              • 2011-04-21
              • 2020-02-03
              • 1970-01-01
              • 1970-01-01
              • 2017-08-05
              • 1970-01-01
              相关资源
              最近更新 更多