2016-02-24 62 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

相关问题