gpt4 book ai didi

python - 如何根据正则表达式条件编辑文本文件的行?

转载 作者:行者123 更新时间:2023-12-05 02:26:22 25 4
gpt4 key购买 nike

import re

re_for_identificate_1 = r""

with open("data_path/filename_1.txt","r+") as file:
for line in file:
#replace with a substring adding a space in the middle
line = re.sub(re_for_identificate_1, " milesimo", line)

#replace in txt with the fixed line

示例filename_1.txt:

unmilesimo primero
1001°

dosmilesimos quinto
2005°

tresmilesimos
3000°

nuevemilesimos doceavo
9012°

我需要的正确输出文件是这样的:

重写输入 filename_1.txt

un milesimo primero
1001°

dos milesimos quinto
2005°

tres milesimos
3000°

nueve milesimos doceavo
9012°

我需要的正则表达式是什么?在输入文件中将固定行替换到其原始位置的最佳方法是什么?

最佳答案

您可以使用 file.seek(0)转到文件的开头,然后写入数据并截断文件。像这样:

import re

re_for_identificate_1 = "(?<!^)milesimo"

tmp = ""
with open("data.txt", "r+") as file:
for line in file:
line = re.sub(re_for_identificate_1, " milesimo", line)
tmp += line
file.seek(0)
file.write(tmp)
file.truncate()

您要使用的正则表达式是 "(?<!^)milesimo"用“milesimo”替换“milesimo”的每个实例,但不是在一行的开头。

关于python - 如何根据正则表达式条件编辑文本文件的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73821359/

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