我有这段代码可以在值之间进行插值并返回特定 X 和 Y 的 Z 值。我正在尝试打开另一个文件 (world.txt
) 并将该值粘贴到特定名称 新西兰
。
文件的组织方式是
Nx
5
Ny
0.1
Nz
0.8
但我得到的是 givemeZ(0.5,0.04)
而不是值 0.78
您能提出一些解决此问题的想法吗?
import numpy as np
from scipy import interpolate
from scipy.interpolate import griddata
import itertools
from scipy.optimize import curve_fit
xx= 0.15, 0.3, 0.45, 0.5, 0.55
yy= 0.01, 0.02, 0.03, 0.04, 0.05
zz= 0.75, 0.76, 0.77, 0.78, 0.79
tck = interpolate.bisplrep(xx, yy, zz, s=0)
def givemeZ(X,Y):
return interpolate.bisplev(X,Y,tck)
## to replace the value
with open('world.txt', 'r') as file :
filedata = file.read()
# Replace the target string
filedata = filedata.replace('Nz', 'givemeZ(0.5,0.01)')
# Write the file out again
with open('world.txt', 'w') as file:
file.write(filedata)
最佳答案
嗯,是的。您传递filedata.replace
字符串文字'givemeZ(0.5,0.01)'
。您应该将实际值传递给它,并转换为字符串,例如
filedata = filedata.replace('Nz', str(givemeZ(0.5,0.01)))
根据详细信息,您可能无需调用 str()
即可逃脱 - 我不确定 replace
是否能顺利处理非 >str
参数可以转换为 str
。不过,自己明确地进行转换应该可行。
要替换下一行,您需要一些在循环中运行的逻辑 - 我认为您无法纯粹通过 replace
来完成此操作。你可以这样做:
new_lines = []
previous_line = ''
with open('world.txt', mode = 'r') as f:
for current_line in f:
if previous_line == 'Nz':
new_lines.append(str(givemeZ(0.5,0.01)))
else:
new_lines.append(current_line)
previous_line = current_line
new_text = '\n'.join(new_lines)
然后,您可以将新文本写回 world.txt
- 请注意,您在此处执行的操作,即使在原始代码中,也不会修改实际文件,而只是修改 Python 字符串内存中。
关于python - 如何替换python中特定单词下的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47241571/