Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

find a number in a certain environment in a file and modify it

I have a large file which contains many occurences of certain syntax: (width 0.15).

The number 0.15 can be any floating point number. I wish to find all instances of these numbers and modify them. I know how to modify them using float('0.15')+modifier and also I know how to make a string of the result again.

I have trouble finding the numbers. I looked at the re module but don’t quite know how to match the numbers themselves and not include the environment with the match.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So I know how to match all the occurrences of the entire environment (width 0.15) using re. I know how to modify the number string. But I don’t know how to match for the actual number within the environment. How to do this ?

>Solution :

IIUC, you could use lookarounds:

s = '(width 0.15)'

match = re.search('(?<=\(width )\d+(?:\.\d*)?(?=\))', s)

output:

match.group()
# '0.15'

For all occurrences + conversion to float:

out = list(map(float, re.findall('(?<=\(width )\d+(?:\.\d*)?(?=\))', )s))

output:

[0.15]

regex:

(?<=\(width )  # match should be preceded by "(width "
\d+            # one or more digits
(?:\.\d*)?     # optionally, a dot with zero or more digits
(?=\))         # match should be followed by ")"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading