简体   繁体   中英

How to replace a specific regex group using re.sub with custom text?

I have the following text:

'The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.'

I'm trying to replace each word with user input. I am using regular expressions to match the words and get them to a list.

I am using re.sub to replace the userinput with the matched regex group. But is there a way I can only replace the first matched group, or second or third?

NOUN comes up twice, so in my for loop, I want the user input to only replace regex.group[0] or [1] , for example.

edit You probably will have to iterate over all words, and make a call for each one, whether you want to change it or not. I'm not sure, how you want to treat punctuation, but I guess something along this lines should do:

(It iterates over all maximum-characters literals, which don't contain space in them)

import re

x='The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events.'
y=''
for wrd in re.findall(r"[^ ]+", x):
    z=input(f"found word {wrd}, replace: ")
    if(z!=''):
        y+=f"{z} "
    else:
        y+=f"{wrd} "

print(y)

Ref: https://docs.python.org/2/library/re.html

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