简体   繁体   中英

Find keyword, replace next value in Python

I have an input file I want to duplicate with some of the parameters changed. This is a simplified version of the input file:

Temperature = 100
Density = 8
Expansion factor = 1.0

I am trying to write a script that will search through the input file, find a keyword (eg temperature/density), then change the next value after the keyword. I have a series of for loops set up for each keyword but I can't work out how to edit the next value after the keyword. I think I need regex but this is all I have so far:

regex = r"Temperature\s(.*)"
re.findall(regex, file)

I would also like to ignore how many spaces there are in the input file if possible - eg these three lines would all appear the same:

Temperature        =    100
Temperature=100
Temperature = 100

If that's possible!

Something like

your_new_text = re.sub(r"(Temperature\s*=\s*)[^\n]+", "\\1TheNewValue", input_file.read())

should do the trick. Replace Temperature with whatever you are searching for and TheNewValue with whatever you want in it's place

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