在python

时间:2016-02-24 09:09:37

标签: python-2.7

f = open("info.txt",'r')
filedata = f.read()
f.close()

newdata = filedata.replace("opdut_decoded.wav","a88.wav")

f = open("info.txt",'w')
f.write(newdata)
f.close()

这是我只替换一个单词的示例代码。

我需要从文本文件中找到一个单词,并通过查找单词逐行替换/重命名该单词与另一个文本文件。

需要继续进行多行重命名。 python中有什么方法可以。请你指导我。

新更新:

  1. 我有第一个文本文件,这些行有些文字a8.ec3 opdut_decoded,sometext a9.ec3 opdut_decoded,sometext a18.ec3 opdut_decoded,sometext LFE1.ec3 opdut_decoded,sometext LFE7.ec3 opdut_decoded,sometext LFE9.ec3 opdut_decoded,sometext a19.ec3 opdut_decoded

  2. 第二个文本文件包含这些行。

    0a.ec3,11.ec3,2c.ec3,3d.ec3,4e.ec3,5f.ec3,6e.ec3

  3. 我需要更换" -opdut_decoded.wav"使用" 0a.ec3",然后使用第二行-opdut_decoded.wav"使用" 1b.ec3"。同样我需要替换文本文件中的所有行。

    更新代码:

    import re
    with open("Rename_Changes_Details2.txt") as openfile:
     for line in openfile:
       for part in line.split():
           if "ec3" in part:
             print part
    new_words = [part]  #This includes a new data in line by line  
    infile = open('out_New.txt','r')    
    data = infile.read()    
    matches = re.findall(r'(opdut_decoded)',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()
    

    输入文件:

    0A

    图1b

    2C

    3D

    我有一个包含以下行的文本文件

    1. -c0 -k2 -w1 -x1.0 -y1.0 -ia8.ac3 -opdut_decoded.wav
    2. -c0 -k2 -w1 -x1.0 -y1.0 -ia9.ac3 -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
    5. 我想用" -opdut_decoded.wav"替换上面给定的输入行。在这样的每一行

      1. -c0 -k2 -w1 -x1.0 -y1.0 -ia8.ac3 -0a.ac3
      2. -c0 -k2 -w1 -x1.0 -y1.0 -ia9.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

3 个答案:

答案 0 :(得分:0)

试试这个,

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

希望这会有用

答案 1 :(得分: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()

答案 2 :(得分: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()