2015-11-06 50 views
0

我需要能夠查找字符串列表中的行數和空行數。查找字符串列表中的行數和空行數量

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() 

也可以使用什麼方法來打印出每行的平均字符數和每個非空行的平均字符數?

+1

您文本變量?沒有一個對我來說是空的 – Andy

+0

'def stats(text:list):'correct? –

+0

'\ n'中的空行 – SystemofaCode

回答

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 
>>> 
0

簡易版(即不依賴於輸入,甚至是一個列表,將與可迭代的工作):你會考慮什麼在一個空行

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