Python Forum
Matching whole words in find/replace script - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Matching whole words in find/replace script (/thread-3947.html)



Matching whole words in find/replace script - greektranslator - Jul-10-2017

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)



RE: Matching whole words in find/replace script - wavic - Jul-10-2017

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



RE: Matching whole words in find/replace script - Ofnuts - Jul-10-2017

(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)


RE: Matching whole words in find/replace script - greektranslator - Jul-11-2017

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).


RE: Matching whole words in find/replace script - greektranslator - Jul-11-2017

I found it

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