2017-05-06 59 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])