2017-05-06 52 views
1

我有一个文本文件,它看起来有点像这样的每一行执行不同的操作:的Python:在文档

line 1 
line 2 
line 3 
line 4 

line 1 
line 2 
line 3 
line 4 

(etc) 

在每line 1我想执行特定的操作,并在每个line 2一个不同的操作等线路重复(包括空格)的模式保存整个文件,所以目前我只是有重置在每个空行和一堆if声明计数器:

if counter == 1: 
    this(line) 
elif counter == 2: 
    that(line) 
elif etc 

我的问题,是有更高效,更Pythonic的方式来做到这一点?

谢谢!

+0

有总是段落之间空一行? –

+0

是的。我刚编辑我的职务,以反映这 – Wmbuch

+0

没有'在Python之开关语句,但有一些方法来达到同样的。如果你不想一堆'elif's看看http://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python。 – JohanL

回答

4

你可以尝试的功能列表上查找:

line_processors = [ 
    lambda ln: print("line 1 of paragraph:", ln), 
    lambda ln: print("line 2 of paragraph:", ln), 
    lambda ln: print("line 3 of paragraph:", ln), 
    lambda ln: print("line 4 of paragraph:", ln), 
    lambda ln: print("blank line:", ln), 
] 

with open("myfile.txt") as f: 
    for i, line in enumerate(f): 
     line_processors[i % 5](line) 
0

可以读取所有文件的线条和创建行的列表。之后,你只需要操作你的列表索引。

with open(fname) as f: 
    content = f.readlines()  
content = [x.strip() for x in content] 

# this(content[0]) 
# that(content[1])