Python Forum

Full Version: Matching whole words in find/replace script
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I use the code below through Notepad++ but I cannot make it match whole words

with open('C:/Temp/Substitutions.txt') as f:
    for l in f:
        s = l.split()
        editor.replace(s[0], s[1])
I also tried:

editor.pyreplace(r'\b' + s[0] + r'\b', s[1])
and

editor = re.sub(r'\b' + s[0] + r'\b', s[1], editor)
What exactly do you want to achieve? Matching a whole word or replace one with another.
with open('C:/Temp/Substitutions.txt') as f:
    for line in f:
        if word in line.lower(): # lower is an option here if you want case insensitive matching 
            # do something
(Jul-10-2017, 07:10 PM)greektranslator Wrote: [ -> ]I use the code below through Notepad++ but I cannot make it match whole words

with open('C:/Temp/Substitutions.txt') as f:
    for l in f:
        s = l.split()
        editor.replace(s[0], s[1])
I also tried:

editor.pyreplace(r'\b' + s[0] + r'\b', s[1])
and

editor = re.sub(r'\b' + s[0] + r'\b', s[1], editor)
This works for me
Output:
>>> re.sub(r'\b'+'CD'+r'\b','XX','ABCD CD CDAB ABCDEF CD') 'ABCD XX CDAB ABCDEF XX'
So I would suspect that the contents of s[0] aren't what you think they are (you don't even trim() the input lines)
On the C:/Temp/Substitutions.txt file I have a list of words separated by space. I want to match a whole word on the left, and replace it with the whole word on the right of the list. For example, if in my substitutions file there is

comp [[comp]]

I do not want it to match words like

computer
uncompare

but only instances of the word "comp" (the word may be preceded and followed by punctuation of course).
I found it

editor.rereplace(r'\b' + s[0] + r'\b', s[1])