簡體   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

示例filename_1.txt

unmilesimo primero
1001°

dosmilesimos quinto
2005°

tresmilesimos
3000°

nuevemilesimos doceavo
9012°

我需要 obtiene 的正確 output文件是這樣的:

重寫輸入filename_1.txt _1.txt

un milesimo primero
1001°

dos milesimos quinto
2005°

tres milesimos
3000°

nueve milesimos doceavo
9012°

我需要什么正則表達式?在輸入文件的原始位置替換固定線的最佳方法是什么?

您可以使用file.seek(0)到 go 文件開頭,然后寫入數據並截斷文件。 像這樣:

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”,但不在行首。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM