2016-02-24 63 views
1

輸入文件:字從文本文件替換到另一個一行一行在Python

0A

1B

2C

3D

我有一個文本文件這些行下面

  1. -c0 -k2 -w1 -x1.0 -y1.0 -ia8.ac3 -opdut_decoded.wav,opdut_decoded.wav,opdut_decoded.wav
  2. -c0 -k2 -w1 -x1.0 -y1.0 -ia9.ac3 -opdut_decoded.wav,opdut_decoded.wav,opdut_decoded.wav
  3. -c0 -k2 -w1 -x1.0 -y1.0 -ia18.ac3 -opdut_decoded.wav
  4. -c0 -k2 -w1 -x1.0 -y1.0 -iLFE1.ac3 -opdut_decoded.wav

我想通過 「-opdut_decoded.wav」 中的每一行,以取代上述給定的輸入線這樣

  1. -c0 -k2 -w1 -x1.0 -y1.0 -ia8.ac3 -0a.ac3,0a.ac3,0a.ac3
  2. -c0 -k2 -w1 -x1.0 -y1.0 - ia9.ac3 -1b.ac3,1b.ac3,1b.ac3
  3. -c0 -k2 -w1 -x1.0 -y1.0 -ia18.ac3 -2c.ac3
  4. -c0 -k2 -w1 - X1.0 -y1.0 -iLFE1.ac3 -3d.ac3
+1

你能舉一個輸入/輸出數據的例子嗎? – yael

+0

例如:對於該文本文件中的所有行,我有一個文本文件,其中包含行「xxxxxxxxxx opdut_decoded」。我還有另一個文本文件,其中包含行「example1」,「example2」,「example3」等行。在這裏,我需要在第一個文本文件中找到單詞「opdut_decoded」,並將其重命名爲第二個文本文件的第一行。類似地,需要使用第二個文本文件行重命名所有行。這裏的「xxxxxxxxx」表示前面的文本「opdut_decoded」 – lotus

+0

我把上面的細節分享爲「新更新:」 – lotus

回答

0
this is how I would construct the list with your input file 
import re  
    rep_file = open('in2','r') 
    new_words = [] 
    for line in rep_file: 
     line = line.strip() 
     new_words.append(line + '.ec3') 

    infile = open('in.txt','r')  
    data = infile.read()  
    matches = re.findall(r'(opdut_decoded\.wav)',data)  
    i = 0  
    for m in matches: 

     data = re.sub(m,new_words[i],data,1) 
     i += 1 

    out = open('out.txt','w') 
    out.write(data)  
    out.close() 
+0

謝謝mr.yael。這是我的工作,因爲我需要 – lotus

+0

line.strip()除去\ n和其它非可見字符 – yael

+0

數據=應用re.sub(米,new_words [I],數據,1) - 與匹配替換m的單次出現word in new_words – yael

0

試試這個,

f = open('info.txt', 'r+') 
filedata = f.read().replace("opdut_decoded.wav", "a88.wav") 
f.write(filedata) 
f.close() 

希望這將工作

0
import re  
    new_words = ['0a.ec3' , '1b.ec3' ,'2c.ec3' ,'3d.ec3' , '4e.ec3' , '5f.ec3' , '6e.ec3']  
    infile = open('in.txt','r')  
    data = infile.read()  
    matches = re.findall(r'(opdut_decoded\.wav)',data)  
    i = 0  
    for m in matches: 

     data = re.sub(m,new_words[i],data,1) 
     i += 1 

out = open('out.txt','w') 
out.write(data)  
out.close() 
+0

如果是這樣,我認爲他需要在同一個文件 – Kjjassy

+0

中執行此操作,或者關閉in文件,重新打開它以便寫入和轉儲數據,或者以rw打開,尋找開頭並轉儲數據吧。 – yael

+0

正如我所說的,要麼像我一樣手動定義你的列表,要麼通過從文件中讀取來構建你的new_word列表,你的錯誤意味着你的new_word列表比文件中要被替換的單詞數量更多。 – yael

相關問題