[英]Python re.sub appends string instead of replacing it
我是Python的新手,并且坚持使用正则表达式替换。 我正在解析一个包含如下语句的设置文件:
set fmri(convolve7) 3
设置文件用作模板。 脚本解析模板,并写入具有更新设置的新设置文件。
我程序的主要结构是
for line in infile:
if condition = true
for each in listofelements
if re.search(each, line):
print(re.sub(r"\d+", "0", line), file=outfile, end='') # double output
if re.search(somethingelse, line):
print(re.sub(templatesubid, i, line), file=outfile, end='')# normal substitution
等等
for循环中的替换会导致输出翻倍,而for循环之外则不会。 for循环似乎使用正确的替换字符串插入换行符,即
set fmri(convolve7) 0
set fmri(convolve7) 3
其他替换按预期工作,但代码相同。 是因为for循环导致此双输出吗?
看起来相关的代码在底部:
for line in infile:
if len(subparamlist) > 0:
for j in subparamlist:
query = j.replace(")", "\)").replace("(", "\(")
if re.search(query, line):
print(re.sub(r"\d+", "0", line), file=outfile, end='') #trouble!
if re.search(templatesubid, line) and re.search('feat_files\(', line) or re.search('\(custom', line) : # correct the subjectID
print(re.sub(templatesubid, i, line), file=outfile, end='')
elif re.search(str(nptslist[2]), line): # correct the number of timepoints
print(re.sub(str(nptslist[2]), str(nvols[0]), line), file = outfile, end='')
else:
print(line, file=outfile, end='') # if nothing to do, just copy the line to the new text file.
我认为问题在于,您要同时在顶部的if
语句中打印(将0
替换为该行),然后在其下面的if/elif/else
块的一个分支中再次打印。 结果是某些(或全部)行被加倍。
我实际上对代码的理解不够好,无法找到适当的解决方案,但是可能的开始可能是将if
您已将“更正subjectID”注释为elif
, if
可以将其更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.