Python:替换某行下的字符串

Python: Replace string under a certain line

抱歉写了,通常我会尽量避免无用的问题,但我已经四处寻找了好几天都没有找到问题的答案。

基本上我在 .txt 文件中有这段代码:

<item name="Find_this_keyword">
ente<value type="vector">[-0.1 0.2 0.3 1.4]
</item>

此行在与此类似的一千行内,仅在该关键字方面有所不同。所以基本上我希望 python 更改带有该关键字的行下的行。 我需要用其他 4 个数字更改向量中的 4 个数字。

你有什么线索吗?

感谢您的宝贵时间

你可以试试这样的方法。

code.txt <- 代码文件

new_vals = [1, 2, 3, 4]
f1 = open('code.txt', 'r')
f2 = open('code_out.txt', 'a+')
for line in f1:
    newline = line
    if 'ente<value type="vector">' in line:  # check line by line and look if the prefix matches
         newline = 'ente<value type="vector">' + f'[{new_vals[0] {new_vals[1]} {new_vals[2]} {new_vals[3]}]'
    # replace the new line
    f2.write(newline)

f1.close()
f2.close()

使用正则表达式查找模式并替换值:

import re

pattern = '\[.+\]'
replace = '[num1, num2, num3, num4]'

file = open('code.txt', 'w')
    for line in file:
    if 'ente<value type="vector">' in line:
        re.sub(pattern, replace, line)

只需用您的新值替换 num1num2num3num4

如果您不将它们用于任何数学运算,请使用字符串格式。