简体   繁体   English

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

[英]How to edit lines of a text file based on regex conditions?

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

Example filename_1.txt :示例filename_1.txt

unmilesimo primero
1001°

dosmilesimos quinto
2005°

tresmilesimos
3000°

nuevemilesimos doceavo
9012°

The correct output file that I need obtiene is this:我需要 obtiene 的正确 output文件是这样的:

Rewrited input filename_1.txt重写输入filename_1.txt _1.txt

un milesimo primero
1001°

dos milesimos quinto
2005°

tres milesimos
3000°

nueve milesimos doceavo
9012°

What is the regex that I need and what is the best way to replace the fixed línes in their original positions in the input file?我需要什么正则表达式?在输入文件的原始位置替换固定线的最佳方法是什么?

You can use file.seek(0) to go beginning of the file, then write data and truncate the file.您可以使用file.seek(0)到 go 文件开头,然后写入数据并截断文件。 Like this:像这样:

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()

The regex you want to use is "(?<!^)milesimo" to replace every instance of "milesimo" with " milesimo" but not at the beginning of a line.您要使用的正则表达式是"(?<!^)milesimo" ,将“milesimo”的每个实例替换为“milesimo”,但不在行首。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM