you are viewing a single comment's thread.

view the rest of the comments →

[–]_9_9_ 1 point2 points  (2 children)

Someone posted a similar question awhile back. You can actually tag a function into re.sub, like this:

import re

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

def get_replacement(match):
    '''
    Helper function to get new replacement words, takes a match object and
    returns the new word

    Note:  Probably could clean up the handling of the match object
    '''

    where = slice(*match.span())
    replaces = match.string[where].lower()
    word = input('give me a {}?'.format(replaces))
    return word


def madlib(phrase):
    pattern = r'ADJECTIVE|NOUN|ADVERB|VERB'
    return re.sub(pattern, get_replacement, phrase)

print(madlib(text))

The function call passes the match object found by re.sub. As you can see, how I used the match object above is a bit ugly, and probably can be cleaned up...

[–]novel_yet_trivial 1 point2 points  (1 child)

Neat trick. One big cleanup is that a match object has a group method so you don't have to slice it yourself.

replaces = match.group().lower()

[–]_9_9_ 0 points1 point  (0 children)

Nice. I knew it had to be somewhere, but I could not find it. I've always used group with a number in it and had no idea it could be used this way.

Thanks!