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

标签 python python-3.x regex regex-group writefile

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/

相关文章:

python - 更改 conda 默认 python 版本

python - 如何在首页显示子页面的子页面? (鹡鸰/ Django )

python - 使用特定列估算 scikit-learn 中的分类缺失值

python-3.x - Pygame TypeError : 'int' object is not callable

Python正则表达式拆分多个匹配项

java - 我无法分离 HTTP 正文 header

python - 在Python中导入elasticsearch.helpers时出现ImportError

python - 如果 python 中的每个列表中都存在一个元素,如何有效地连接列表

Python - 在 "detached"进程中生成函数的最佳方式

mysql - 如何将此正则表达式转换为 mysql posix