gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:59:25 25 4
gpt4 key购买 nike

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

NAME1   184,743 184,439 14,305NAME2   84,343  64,437  36,335NAME3   154,543 174,439 38,385

I want to fill down all empty lines (including lines with only tabs and/or spaces) with the non-empty line above it. The final output should look like this:

NAME1   184,743 184,439 14,305NAME1   184,743 184,439 14,305NAME1   184,743 184,439 14,305NAME1   184,743 184,439 14,305NAME2   84,343  64,437  36,335NAME2   84,343  64,437  36,335NAME2   84,343  64,437  36,335NAME2   84,343  64,437  36,335NAME2   84,343  64,437  36,335NAME3   154,543 174,439 38,385NAME3   154,543 174,439 38,385NAME3   154,543 174,439 38,385NAME3   154,543 174,439 38,385

I tried this code but I can't figure how to make it work as I am new to Python. The regular expression works in Notepad++ but not in 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 ]+|)$","\1\2\1",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()

关于python - 在Python中使用正则表达式递归替换某些行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52576047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com