2013-07-31 129 views
0

中的所有行[fromString,toString]我想用給定的字符串替換我的文本文件中的某段文本。例如,給出下面的文件內容:替換文件

1 
---From here--- 
2 
---To here--- 
3 

我想編寫在以這種方式的格式開始一個python函數:

replaceSection('pathToFile','---From here---\n','---To here---\n','Woo Hoo!\n') 

這應該在原始文件更改爲:

1 
Woo Hoo! 
3 

我想出了一個簡單的實現(下圖),但我相信它也有一些缺點,我想知道是否有一個更簡單的實現:

  • 的代碼很長,這使得它的理解有點麻煩
  • 我遍歷了兩次代碼(而不是就地更換) - 這似乎效率不高
  • 這是同一個實現我會使用我的C++代碼,我想Python有一些隱藏美女,將使實施更加優雅

    def replaceSection(pathToFile,sectionOpener,sectionCloser,replaceWith = ''): 
        ''' 
        Delete all the lines in a certain section of the given file and put instead a customized text. 
    
        Return: 
        None if a replacement was performed and -1 otherwise. 
        ''' 
        f = open(pathToFile,"r") 
        lines = f.readlines() 
        f.close() 
        if sectionOpener in lines: 
         isWrite = True # while we are outside the block and current line should be kept 
         f = open(pathToFile,"w") 
         #Write each line until reaching a section opener 
         # from which write nothing until reaching the section end. 
         for line in lines : 
          if line == sectionOpener: 
           isWrite = False 
          if isWrite: 
          # We are outside the undesired section and hence want to keep current line  
           f.write(line) 
          else: 
           if line == sectionCloser: 
            # It's the last line of the section 
            f.write(replaceWith) 
            ) 
            isWrite = True 
           else: 
            # Current line is from the block we wish to delete 
            # so don't write it. 
            pass 
         f.flush() 
         f.close() 
        else: 
         return -1 
    
+3

也許更適合http://codereview.stackexchange.com – sloth

+0

@ Dominic Kexel - 感謝您的評論。代碼實際上與問題無關,但是隻是回答「你試過了什麼?」並使期望的行爲更清晰。你還認爲它應該轉移到codereview?編輯問題並刪除我的代碼?謝謝! –

回答

1

下面是一個itertools基礎的方法:

from itertools import takewhile, dropwhile, chain, islice 

with open('input') as fin, open('output', 'w') as fout: 
    fout.writelines(chain(
     takewhile(lambda L: L != '---From here---\n', fin), 
     ['Woo Hoo!\n'], 
     islice(dropwhile(lambda L: L != '---To here---\n', fin), 1, None) 
     ) 
    ) 

所以,直到我們得到了來自標誌,寫出來的原線,那麼線(S)你想,那麼,不顧一切,直到結束標誌,並寫下其餘的行(跳過第一個,因爲它將是結束標記)...

+0

感謝您的itertools提示。 –

1

在這裏你可以隨便找個地方您2種模式是:這個界定文本的一部分,你不得不用你的新模式來替代它:

>>> f = my_file.readlines() 
>>> beg = f.index('---From here---') 
>>> end = f.index('---To here---') + len('---To here---') 
>>> print f.replace(f[beg:end], 'Woo woo !') 
1 
Woo woo ! 
3 

當心你的第二個分隔符的長度(因此f.index('---To here---') + len('---To here---'))的。