2013-11-28 50 views
0

我有一個非常大的JavaScript文件,我試圖分析。該文件有很多代碼,刪除了新行,並且很難分析文件,因此我使用替換函數來查找;的所有實例,並將其替換爲;\u000A(\ u000A是新行的unicode)。這解決了我的問題,程序變得更具可讀性。但是我現在有另一個問題:每個for循環都被改變了。如何在python中讀取文件時檢查下一行,並在其末尾去除換行符?

例如:

for(i=0; i<someValue; i++)

得到了改變,以

for(i=0; 
i<someValue; 
i++) 

我想用Python語言編寫一個程序來格式化這個錯誤。我的想法是沿線:

for line in open('index.html', 'r+'): 
    if line.startswith('for(') and line.endswith(';'): 
     line.strip('\n') 

不過,我不知道我該用什麼代碼剝奪下一行換行符作爲for循環只會一次讀取一行。任何人都可以請建議我需要做什麼?

回答

1

Python文件對象是一個迭代,你可以要求它的下一行,而循環:

with open(inputfilename) as ifh: 
    for line in ifh: 
     if line.startswith('for(') and line.endswith(';\n'): 
      line = line.rstrip('\n') + next(ifh).rstrip('\n') + next(ifh) 

它使用next() functionifh文件對象中檢索接下來的兩項並將它們添加到當前行。之後的外部循環將繼續執行。

爲了說明,看看這個迭代循環的輸出:

>>> lst = [1, 2, 3, 4] 
>>> lst_iter = iter(lst) 
>>> for i in lst_iter: 
...  print i 
...  if i == 2: 
...   print 'skipping ahead to', next(lst_iter) 
... 
1 
2 
skipping ahead to 3 
4 

這裏next()先進lst_iter迭代到下一個項目,然後將外循環for與之後的下一個值繼續進行。

您的下一個問題是原地重寫文件;您無法同時讀取和寫入同一個文件,並希望只替換正確的部分。緩衝和不同的線路長度會妨礙您的發展。

使用fileinput module處理替換文件的內容:

import sys 
import fileinput 

for line in fileinput.input(inputfilename): 
    if line.startswith('for(') and line.endswith(';'): 
     line = line.rstrip('\n') + next(ifh).rstrip('\n') + next(ifh) 
    sys.stdout.write(line) 

或使用我in-place file rewriting context manager

from inplace import inplace 

with inplace(inputfilename) as (ifh, ofh): 
    for line in ifh: 
     if line.startswith('for(') and line.endswith(';'): 
      line = line.rstrip('\n') + next(ifh).rstrip('\n') + next(ifh) 
     ofh.write(line) 
+0

我想這就是我正在尋找的。 – TheRookierLearner

+0

ifh.next()'是否有'next(ifh)'這個選項?或者它們是否相同? – crennie

+1

@crennie:在Python 3中,'.next()'被重命名爲'.__ next __()'。該函數正確處理任一方法。 'next()'函數也可以給你一個默認值。 –

0

您可以使用一個計數器,像這樣:

cnt = 2 
for line in open('index.html'): 
    if(line.startswith('for(') and line.endswith(';\n')): 
     cnt = 0 
    if cnt < 2: 
     line = line.strip('\n') 
     cnt += 1 
+0

Python不需要分號。 –

+0

是的,先生,我刪除它 – PasteBT

+0

看看語法突出顯示,你的代碼仍然無法工作。 –

相關問題