【问题标题】:Count number of lines in a txt file with Python excluding blank lines使用 Python 计算 txt 文件中的行数,不包括空行
【发布时间】:2012-05-20 12:51:08
【问题描述】:

我希望计算 .txt 文件中的行数,如下所示:

apple
orange
pear

hippo
donkey

其中有用于分隔块的空行。根据上面的示例,我正在寻找的结果是五(行)。

我怎样才能做到这一点?

作为奖励,很高兴知道有多少块/段落。所以,根据上面的例子,这将是两个块。

【问题讨论】:

  • 必须是python吗? grep . filename | wc -l 会很容易地给你台词。
  • @Daenyth 这是一个更大的 Python 脚本的一部分,所以理想情况下是的。
  • @larsmans 这是一个有趣的链接。找了好久,找到了很多获取行的例子,但是没有找到排除空格的例子。

标签: python


【解决方案1】:
non_blank_count = 0

with open('data.txt') as infp:
    for line in infp:
       if line.strip():
          non_blank_count += 1

print 'number of non-blank lines found %d' % non_blank_count

更新:重新阅读问题,OP 想要计算 non-blank 行..(叹气..感谢@RanRag)。 (我需要从电脑上休息一下……)

【讨论】:

  • 这不起作用。空行返回为"\n",而不是""
  • Junuxx,而不是 infp.readlines(),因为它会一次读取所有行,而不是遍历行。
  • @Levon:我认为用户想要计算文件中不包括空白行的行数。他不想数blank lines的数量。
  • @Junuxx 点了,但我认为逐行方法可能更适合潜在的大文件,因为readlines 将整个文件读入列表/内存
  • 另一种方式:non_blank_count = sum(1 for line in open("data.txt") if line.strip())
【解决方案2】:

计算非空行数的一种简单方法是:

with open('data.txt', 'r') as f:
    lines = f.readlines()
    num_lines = len([l for l in lines if l.strip(' \n') != ''])

【讨论】:

    【解决方案3】:

    我很惊讶地发现还没有一个干净的 Pythonic 答案(截至 2019 年 1 月 1 日)。许多其他答案创建了不必要的列表,以非pythonic方式计数,以非pythonic方式循环文件的行,不正确关闭文件,做不必要的事情,假设行尾字符可以只能是'\n',或者有其他较小的问题。

    这是我建议的解决方案:

    with open('myfile.txt') as f:
        line_count = sum(1 for line in f if line.strip())
    

    这个问题没有定义什么是空行。 我对空行的定义: line 是空行当且仅当line.strip() 返回空字符串。这可能是也可能不是您对空行的定义。

    【讨论】:

      【解决方案4】:
      sum([1 for i in open("file_name","r").readlines() if i.strip()])
      

      【讨论】:

        【解决方案5】:

        考虑到空行只包含换行符,避免调用 str.strip 会更快,这会创建一个新字符串,而是使用 str.isspace 检查该行是否仅包含空格,然后跳过它:

        with open('data.txt') as f:
            non_blank_lines = sum(not line.isspace() for line in f)
        

        演示:

        from io import StringIO
        
        s = '''apple
        orange
        pear
        
        hippo
        donkey'''
        
        non_blank_lines = sum(not line.isspace() for line in StringIO(s)))
        # 5
        

        您可以进一步使用str.isspaceitertools.groupby 来计算文件中连续行/块的数量:

        from itertools import groupby
        
        no_paragraphs = sum(k for k, _ in groupby(StringIO(s), lambda x: not x.isspace()))
        print(no_paragraphs)
        # 2
        

        【讨论】:

          【解决方案6】:

          非空行计数器:

          lines_counter = 0
          
          with open ('test_file.txt') as f:
              for line in f:
                  if line != '\n':
                      lines_counter += 1
          

          块计数器:

          para_counter = 0
          prev = '\n'
          
          with open ('test_file.txt') as f:
              for line in f:
                  if line != '\n' and prev == '\n':
                      para_counter += 1
                  prev = line
          

          【讨论】:

            【解决方案7】:

            这段 Python 代码应该可以解决你的问题:

            with open('data.txt', 'r') as f: 
                lines = len(list(filter(lambda x: x.strip(), f)))
            

            【讨论】:

            • 为什么是filtermap?你就不能这样做吗:filter(lambda x:x.strip(),f)
            • 我不知道我是否有充分的理由去import string :)
            • @mgilson:而且,在我匆忙编辑时,我完全忘记了删除那部分:)
            【解决方案8】:

            我会这样做:

            f = open("file.txt")
            l = [x for x in f.readlines() if x != "\n"]
            
            print len(l)
            

            readlines() 将列出文件中的所有行,然后您可以只取那些至少包含某些内容的行。 对我来说看起来很简单!

            【讨论】:

              【解决方案9】:

              很直接!我相信

              f = open('path','r')
              count = 0
              for lines in f:
                  if lines.strip():
                      count +=1
              print count
              

              【讨论】:

                【解决方案10】:

                我的一个班轮是

                print(sum(1 for line in open(path_to_file,'r') if line.strip()))
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2023-03-12
                  • 2012-09-26
                  • 1970-01-01
                  相关资源
                  最近更新 更多