Python:替换某行下的字符串

2024-09-29 23:17:15 发布

您现在位置:Python中文网/ 问答频道 /正文

很抱歉写信,一般来说,我会尽量避免提出无用的问题,但我已经四处寻找了好几天,没有找到问题的答案

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

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

这一行在一千行中,类似于这一行,只在那个关键字上有所不同。因此,基本上我希望python用该关键字更改行下的行。 我需要将向量中的4个数字与其他4个数字一起更改

你有什么线索吗

谢谢你的时间


Tags: 文件答案代码nametxtvaluetype数字
2条回答

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

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

如果你不想在任何数学中使用它们,就让它们成为字符串格式

你可以试试这样的

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

相关问题 更多 >

    热门问题