我想要计算一个像这样的 .txt 文件中行数:
apple
orange
pear
hippo
donkey
当有空行用于分隔块时,我想要的结果是五个(行),基于上面的示例。
我该如何实现这个目标?
作为额外奖励,知道有多少个块/段落会很好。因此,基于上面的示例,那将是两个块。
我想要计算一个像这样的 .txt 文件中行数:
apple
orange
pear
hippo
donkey
当有空行用于分隔块时,我想要的结果是五个(行),基于上面的示例。
我该如何实现这个目标?
作为额外奖励,知道有多少个块/段落会很好。因此,基于上面的示例,那将是两个块。
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
更新:重新阅读了问题,楼主想要计算非空行数...(叹气...感谢 @RanRag)。(我需要从电脑中休息一下...)
readlines
会将整个文件读入列表/内存中。 - Levonnon_blank_count = sum(1 for line in open("data.txt") if line.strip())
。该代码用于计算"data.txt"文件中非空行的数量。 - jfs一种简短的计算非空行数的方法可能是:
with open('data.txt', 'r') as f:
lines = f.readlines()
num_lines = len([l for l in lines if l.strip(' \n') != ''])
'\n'
,或者存在其他较小的问题。with open('myfile.txt') as f:
line_count = sum(1 for line in f if line.strip())
这个问题没有定义什么是空行。我的定义是:line
是一行空行如果且仅当line.strip()
返回空字符串。这可能与您的定义不同。
考虑到空白行只包含换行符,避免调用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.isspace
与 itertools.groupby
来计算文件中连续行/块的数量:
from itertools import groupby
no_paragraphs = sum(k for k, _ in groupby(StringIO(s), lambda x: not x.isspace()))
print(no_paragraphs)
# 2
sum([1 for i in open("file_name","r").readlines() if i.strip()])
f = open('path','r')
count = 0
for lines in f:
if lines.strip():
count +=1
print count
非空行计数器:
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
with open('data.txt', 'r') as f:
lines = len(list(filter(lambda x: x.strip(), f)))
filter
和 map
?难道你不能只这样做:filter(lambda x:x.strip(),f)
? - mgilsonimport string
:) - mgilson这是我会怎么做:
f = open("file.txt")
l = [x for x in f.readlines() if x != "\n"]
print len(l)
readlines()
会将文件中的所有行制作成一个列表,然后您只需取出那些至少包含一些内容的行即可。对我来说看起来非常简单!
print(sum(1 for line in open(path_to_file,'r') if line.strip()))