如何使用python替换文本文件中特定单词附近的单词
这是我的示例代码,用于在文本文件的所有行中查找特定单词“dut_decoded”,并逐行替换为另一个文本文件的引用具有行线的新名称) 进口再 new_words = []如何使用python替换文本文件中特定单词附近的单词
rep_file = open('Rename_Changes_Details.txt','r')
for line in rep_file:
line = line.strip()
new_words.append(line)
infile = open('Filter_Lines.txt','r')
i = 0
out = open('ip_list.txt','w')
for inlines in infile:
inlines = re.sub('dut_decoded',new_words[i],inlines)
out.write(inlines)
i += 1
out.close()
infile.close()
但是,我需要更换的单词的邻近词“OUT =”由新的名字都行。 例如我有这些行的文本文件
1 .-- bass_cut_off = 45 - OUT = sys_alg_oar_bass_extraction_BE45_SR32k0_IN8B0O_SP8F0H.wav
2 .-- bass_cut_off = 0 --out = sys_alg_oar_all_beds_IN10B0O_SP10F2H.wav
3 .-- bass_cut_off = 8 - OUT = sys_alg_oar_bass_extraction_BE80_SR44k1_IN8B0O_SP8F0H.wav
这里我需要接近更换字(sys_alg_oar_bass_extraction_BE45_SR32k0_IN8B0O_SP8F0H.wav) “出=” 在第一line.Like这个过程需要在所有的行,以取代。新名字来自“infile”我我的代码。 这个“infile”有以下几行。
像this.Finally我想这些输出这样。
1 .-- bass_cut_off = 45 - 出= 100
2 .-- bass_cut_off = 0 --out = 101
3 .-- bass_cut_off = 8 - 出= 102
你能指导我这个吗。
正则表达式库具有如下功能替代的匹配部件re.sub(pattern, repl, string)
使用向前看符号(?=...)
和lookbehinds(?< = ...),从而导致
'--bass_cut_off=0 --out=something'
re.sub("(?<=--out=)(.+)(?=\s)", "something", "--bass_cut_off=0 --out=sys_alg_oar_all_beds_IN10B0O_SP10F2H.wav")
在这个例子中,我也可以使用负向预测(?!...)
。同样,你可以使用模式"(?<=--out=)(\w+)"
,并会匹配到单词的末尾,从而留下".wav"
后缀
'--bass_cut_off=0 --out=something.wav'
在这个例子相当于"(?<=--out=)(.+)(?=.wav)"
将不同的单词重新命名为新名称。在这里什么是“\ w”的功能 – lotus
简而言之:任何字母,数字或下划线。更长的描述在https://docs.python.org/2/library/re.html – user2622016
这是否可以在“。”之后包含一个字符。 – lotus
那么,什么是恰恰与当前代码的问题? – jonrsharpe
这只是用一个新的名字来代替一个特定的单词。但是在这里,我想通过一个单词“out =” – lotus