简体   繁体   中英

how to replace a value under specific word in python?

I have this code to interpolate between the values and return Z value for specific X and Y. I am trying to open another file ( world.txt ) and paste the value under specific name Nz .

The way the file is organised is

Nx
5
Ny
0.1
Nz
0.8

But what i am getting is givemeZ(0.5,0.04) instead of the value 0.78

Would you please suggest some ideas of how to fix it?

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)

Well, yeah. You pass filedata.replace the string literal 'givemeZ(0.5,0.01)' . You should pass it the actual value, converted to a string, like

filedata = filedata.replace('Nz', str(givemeZ(0.5,0.01)))

Depending on the details, you may be able to get away without the str() call - I'm not sure if replace will smoothly handle non- str arguments that can be converted to str . Doing the conversion yourself explicitly should work though.


To replace the next line, you need some logic that runs in a loop - I don't think you'll be able to do it purely by a replace . You could do something like this:

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)

You could then write the new text back to world.txt - note that the operations you're doing here, even in your original code, do not modify the actual file, just the Python string in memory.

Your code works as expected, the line

filedata = filedata.replace('Nz', 'givemeZ(0.5,0.01)')

replaces the string Nz with the string givemeZ(0.5,0.01) .

You want to replaze Nz with the return value of givemeZ(0.5,0.01) . Use the following:

filedata = filedata.replace('Nz', str(givemeZ(0.5, 0.01)))

This takes the return value of givemeZ() and converts this value to a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM