2013-01-21 61 views
0

我需要在文本文件中查找「translate」的每個實例並在找到文本後找到4行代碼:如何使用Python在一行中查找字符串並在字符串後面更改n行文字

"(many lines) 
       } 
      } 
     translateX xtran   
      { 
      keys  
       { 
       k 0 0.5678 
       } 
      } 
(many lines)" 

值0.5678需要爲0.它總是比"translate"字符串低4行 該文件最多有大約10,000行。 示例文本文件名:01F.pz2

我還想循環瀏覽文件夾,並對pz2擴展名(最多40個)的每個文件重複該過程。

任何幫助,將不勝感激!

謝謝。

+1

你已經試過......?顯示您在解決問題時所付出的一些努力,錯誤或_code_。 –

回答

1

我不太清楚在文件中替換0.5678的邏輯,因此我使用了一個函數 - 將其更改爲任何您需要的內容,或者更詳細地解釋您想要的內容。最後一個號碼是?只有浮點數?

嘗試:

import os  

dirname = "14432826" 
lines_distance= 4 

def replace_whatever(line): 
    # Put your logic for replacing here 
    return line.replace("0.5678", "0") 

for filename in filter(lambda x:x.endswith(".pz2") and not x.startswith("m_"), os.listdir(dirname)): 
    print filename 
    with open(os.path.join(dirname, filename), "r") as f_in, open(os.path.join(dirname,"m_%s" % filename), "w") as f_out: 
     replace_tasks = [] 
     for line in f_in: 
      # search marker in line 
      if line.strip().startswith("translate"): 
       print "Found marker in", line, 
       replace_tasks.append(lines_distance)     
      # replace if necessary 
      if len(replace_tasks)>0 and replace_tasks[0] == 0: 
       del replace_tasks[0] 
       print "line to change is", line, 
       line_to_write = replace_whatever(line) 
      else: 
       line_to_write = line 
      # Write to output 
      f_out.write(line_to_write) 
      # decrease counters 
      for i, task in enumerate(replace_tasks): 
       replace_tasks[i] -= 1 

代碼中的註釋應該幫助理解。主要概念是列表replace_tasks,記錄下一行修改的時間。

備註:您的代碼示例建議您的文件中的數據是結構化的。閱讀這個結構並在其上工作,而不是在純文本文件上進行搜索和替換的方法肯定會更加節省。

+0

謝謝Thorsten! –

0

托爾斯滕,我重新命名原始文件有.old擴展名與下面的代碼工作:

import os 
target_dir = "." 


# cycle through files 
for path, dirs, files in os.walk(target_dir): 
    # file is the file counter 
    for file in files: 
     # get the filename and extension 
     filename, ext = os.path.splitext(file) 
     # see if the file is a pz2 
     if ext.endswith('.old') : 
      # rename the file to "old" 
      oldfilename = filename + ".old" 
      newfilename = filename + ".pz2" 
      old_filepath = os.path.join(path, oldfilename) 
      new_filepath = os.path.join(path, newfilename) 
      # open the old file for reading 
      oldpz2 = open (old_filepath,"r") 
      # open the new file for writing 
      newpz2 = open (new_filepath,"w") 
      # reset changeline 
      changeline = 0 
      currentline = 0 
      # cycle through old lines 
      for line in oldpz2 : 
       currentline = currentline + 1 
       if line.strip().startswith("translate"): 
         changeline = currentline + 4 
       if currentline == changeline : 
        print >>newpz2,"    k 0 0" 
       else : 
        print >>newpz2,line 
相關問題