【问题标题】:How to check how many line start with digit如何检查有多少行以数字开头
【发布时间】:2016-03-20 13:29:02
【问题描述】:

假设一个字符串'text'代表多行,我如何计算有多少行以数字开头?

def digit_leading_lines(text):
    n = 0
    newlist = text.split()
    for i in range (len(newlist)):
        for j in range (len(newlist[i])):
            if newlist[i][j].isdigit() == True:
                n += 1
    return n 

一旦我用 text = 'AAA\n1st' 对其进行测试,它会给出正确的输出为 1。 但是当我输入 text = "\t4G\nHz\n" 时,这会导致第一行以 tab 开头,并且输出应该是 0。但是,它仍然给我 1 作为输出。

当我测试“0\n0 3\n\n”时,它给了我错误的输出 3。感谢您的帮助。

【问题讨论】:

    标签: python string for-loop split


    【解决方案1】:

    解决办法是:

    def digit_leading_lines(text):
        lines = text.splitlines()
        count = 0
        for line in lines:
            if line and line[0].isdigit():
                count += 1
        return count
    

    【讨论】:

    • 感谢您的帮助。您的代码完全有效。当我将“if line and line[0].isdigit():”更改为“if line[0].isdigit():”时。输出变得不同。你能解释一下吗?
    • 您还应该检查行是否为空(“0\n0 3\n\n”.splitlines() 将返回 ['0', '0 3', ''] )和 'if line' 语句将检查这种情况
    【解决方案2】:

    为什么您的代码不起作用

    那是因为你在每一行的每个字符上循环。您的输出是有意义的,因为它只是计算文件中的位数,而不是 以数字开头的行

    让它发挥作用

    您的问题有很多可能的解决方案,直接的解决方案是逐行迭代,并且只检查每行的第一个字符:

    with open('file') as f:
        lines = f.readlines()
        for line in lines:
            # check if the first character is a digit
            # and increment the count
    

    终生提示:始终调试代码以更好地理解其流程

    【讨论】:

      【解决方案3】:

      使用正则表达式试试这个代码 sn-p:

      data = """
      The volcano is covered by a thick ice cap,
      one of the largest in the tropics,
      5 that has existed since at least the Pliocene and has
      3 undergone several phases of expansion and reduction. As of
      2016, the ice cap is in retreat; one estimate predicts that
      it will disappear by
      2045. The retreat of the Coropuna glaciers threatens the water
      supply of tens of thousands of people,
      and interaction between volcanic activity and glacial effects has
      45 generated mudflows that could be a hazard to surrounding populations
      if the mountain returns to volcanic activity.
      """
      
      rx = re.compile(r"^\d", re.IGNORECASE | re.DOTALL | re.MULTILINE)
      
      count = 0
      for match in rx.finditer(data):
          count += 1
      
      print(count)
      

      输出:5

      data 包含您的多行文本。

      【讨论】:

        【解决方案4】:

        您正在使用 .split() 删除所有空格。相反,请使用.splitlines()。此外,您可以使用生成器表达式来执行此操作:

        def digit_leading_lines(text):
            return sum(1 for line in text.splitlines() if line and line[0].isdigit())
        

        【讨论】:

          【解决方案5】:

          您可以使用 '\n' 参数调用 split 方法,以便它仅根据换行符进行拆分。然后你可以像下面的代码一样简单地检查你的数值。

          def digit_leading_lines(text):
              n = 0
              newlist = text.split('\n')
              for l in newlist:
                  if len(l) and l[0].isdigit():
                      n += 1
              return n
          
          print digit_leading_lines("\t4G\nHz\n")
          

          【讨论】:

            【解决方案6】:

            Python 允许你做你想做的事:对所有行求和,其中第一个字母是一个数字。您可以在数字上下文中使用 False 或空字符串具有值 1 的事实并总结:

            sum(
                (line and line[0]).isdigit() 
                for line in text.splitlines()
            )
            

            当行为空时,您需要(line and line[0]) 来避免IndexError,在这种情况下返回第一个假值(空字符串),它不是数字,因此返回False

            【讨论】:

              猜你喜欢
              • 2016-01-05
              • 1970-01-01
              • 2023-01-01
              • 2018-02-02
              • 2014-12-08
              • 1970-01-01
              • 2019-08-24
              • 2015-04-15
              • 2018-03-01
              相关资源
              最近更新 更多