很抱歉写这篇文章,通常我尽量避免无用的问题,但我已经四处寻找了几天,没有找到我的问题的答案。
基本上,我在一个.txt文件中有这段代码:
<item name="Find_this_keyword">
ente<value type="vector">[-0.1 0.2 0.3 1.4]
</item>
这一行在一千行内,与此类似,只是关键字不同。所以基本上我想让python用这个关键字来改变行下面的行。我需要将向量中的4个数字改为其他4个数字。
你有什么线索吗?
耽误您时间,实在对不起
发布于 2020-04-16 13:33:07
使用正则表达式查找模式并替换该值:
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)
只需用您的新值替换num1
、num2
、num3
、num4
即可。
如果你不想把它们用于任何数学运算,那就让它们以字符串格式存在吧。
发布于 2020-04-16 13:00:35
你可以试试这样的东西。
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()
https://stackoverflow.com/questions/61250596
复制相似问题