在 Python 中使用正则表达式递归替换某些行



我有一个文本文件,想要递归替换所有包含某种正则表达式模式的行,然后将结果保存到新的文本文件中。输入文本文件包含以下内容:

姓名1 184,743 184,439 14,305 姓名2 84,343 64,437 36,335 姓名3 154,543 174,439 38,385

我想用上面的非空行填充所有空行(包括只有制表符和/或空格的行(。最终输出应如下所示:

姓名1 184,743 184,439 14,305 姓名1 184,743 184,439 14,305 姓名1 184,743 184,439 14,305 姓名1 184,743 184,439 14,305 姓名2 84,343 64,437 36,335 姓名2 84,343 64,437 36,335 姓名2 84,343 64,437 36,335 姓名2 84,343 64,437 36,335 姓名2 84,343 64,437 36,335 姓名3 154,543 174,439 38,385 姓名3 154,543 174,439 38,385 姓名3 154,543 174,439 38,385 NAME3 154,543 174,439 38,385

我尝试了这段代码,但我不知道如何让它工作,因为我是 Python 的新手。正则表达式在记事本++中有效,但在IDLE中无效:

import re
fhand = open("/home/user1/Documents/inputtext.txt")
fout = open("/home/user1/Documents/outputtext.txt","w")
for line in fhand:
re.sub("^(S+.*)$(n)^([t ]+|)$","121",line)
fout.write(line)
fout.close()

您可以使用一个简单的循环来跟踪包含任何非空格的最后一行:

last = 'n'
for line in fhand:
# if the line isn't empty after stripping all whitespaces
if line.strip():
# save this line into the variable last for later blank lines to copy from
last = line
# otherwise it's a blank line
else:
# and we should copy from the non-blank line saved in the variable last
line = last
fout.write(line)
fout.close()

最新更新