Hi, I have a little problem.

I want to replace words in a text, but only 'whole words'. That is, I'm looking for a method that changes "cat", but not "catfood".
I know how to do it using re.sub, like this:

re.sub(r'\bword\b', 'change', text)

Only problem is, I'm using a dictionary in an external textfile for this, and while that works fine if I do it straightforward, I haven't found a way to take 'whole words' into account while using the dictionary.

Is this possible? If so, I would really appreciate advice.

>>> test = "cat ate the catfood and went to cat's bed to see cat dreams on catepillars."
>>> test = ' '.join('dog' if word == 'cat' else word for word in test.split())
>>> test
"dog ate the catfood and went to cat's bed to see dog dreams on catepillars."
>>> replacements = {'cat': 'dog'}
>>> test = "cat ate the catfood and went to cat's bed to see cat dreams on catepillars."
>>> ' '.join(replacements[word] if word in replacements else word for word in test.split())
"dog ate the catfood and went to cat's bed to see dog dreams on catepillars."
>>> 

You can use sub() with a method as argument

import re
from functools import partial

repl_dict = {'cat': 'Garfield', 'dog': 'Oddie' }

def helper(dic, match):
    word = match.group(0)
    return dic.get(word, word)

word_re = re.compile(r'\b[a-zA-Z]+\b')
text = "dog ate the catfood and went to cat's bed to see dog dreams on caterpillars"

print word_re.sub(partial(helper, repl_dict), text)

""" my output -->
Oddie ate the catfood and went to Garfield's bed to see Oddie dreams on caterpillars
"""
commented: Elegant partial+function +12

@pytony and Gribouillis - a little bit late reply from me, but thanks a lot for the help. I finally made it work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.