简体   繁体   中英

How can I search for an integer after a string in a document using Python?

I have a document.txt that has a line in it that says something like "randomtext here location 34 randomtexthere".

I know how to replace a word with another word but what if I want to replace the random integer after the word "location"? And maybe give an error if there is no integer after the word.

I can't specify the exact number I want to replace because that number can change. So I'm looking for a way to find the number after "location" and change it to the number I specify.

I'm currently working with something like this:

def replaceid():
    source = "C:/mypath/document.txt"
    oldtext = "oldtexthere"
    newtext = "newtexthere"
    with fileinput.FileInput(source, inplace=True, backup='.bak') as file:
        for line in file:
            print(line.replace(oldtext, newtext), end='')

I can't specify the exact number I want to replace because that number can change

This says you want a regular expression to describe the pattern "a number" without writing any specific number, and to say that it must be found after 'location'".

It might look like this:

import re

s = "randomtext here location 34 randomtexthere"

pattern = r'(?<=location )\d+'       # match a number 
                                     # i.e. a digit (\d) then any more digits (+)
                                     # Only if it comes after 'location '
                                     # (but don't match that word)


if re.search(pattern, s):            # Search for the pattern in the string
  print(re.sub(pattern, '200', s))   # replace the pattern match with new number
else:
  print("Number not found")          # or print an error message

And in your case, do that re.search for each line in the file.

Regex can do this. Split won't work because you have to specify a value.

import re

for line in document:
    re.sub("\d{0,3}", replacementNumber, line)

Here we loop through the lines in the file looking for strings that match the pattern we pass to re.sub. We told it to look for any digits up to 3 in length [IE 123, 23, 1 would count] and replace them with the number you provide in replacementNumber.

Something like this, and it could be done shorter (or longer), no function here just an example of replacing the integer with some other random integer. Add more logic if it needs to follow a particular word.

from random import randint

s = "randomtext here location 34 randomtexthere"

l = s.split(' ')
new_l = []
for el in l:
    if el.isdigit():
        new_l.append(randint(0, 99))
    else:
        new_l.append(el)

print(new_l)

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