查找字符串列表中的行数和空行数

时间:2015-11-06 02:25:53

标签: python python-3.x

我需要能够在字符串列表中找到行数和空行。

text = [
'Hi my name is bob',
'hi my name is jill',
'hi my name is john',
'hi my name jordan']

我想出了

def stats(text: list):
    for i in range(len(text)):
        lines = (i + 1)
    for i in text:
        if i == '\n':
            print(range(len(i)))

找到线条的数量但是找到空行的数量不起作用

我需要使用这些方法吗?

result = []
.append()

我还可以使用哪些方法来打印每行的平均字符数和每非空行的平均字符数?

2 个答案:

答案 0 :(得分:1)

也许只是使用列表理解?这是一个演示:

>>> f = open('file')
>>> l = f.readlines()
>>> l
['my name is bob\n',
 '\n',
 'hi my name is jill\n',
 'hi my name is john\n',
 '\n',
 '\n',
 'hi my name jordan\n']   # there is 3 *empty lines* and 4 non-empty lines in this file
>>> len([i for i in l if i == '\n'])
3
>>> len([i for i in l if i != '\n'])
4
>>> 

答案 1 :(得分:0)

简单版本(即使是列表也不依赖于输入;可以使用任何可迭代的版本):

def stats(lines):
    empty = 0
    for total, line in enumerate(lines, start=1):
        empty += not line.rstrip('\r\n')
    return total, empty