Renan Cidale
Renan Cidale

Reputation: 912

Python Script for search and replace with "match words only" option

Py File: named Portuguesetranslator.py

with open('C:/Users/User/Desktop/Portuguesetranslator.txt') as f:
    for l in f:
        s = l.split('*')
        editor.replace(s[0],s[1])

I created that into Python Script inside of Notepad++

Then i have my "database" called Portuguesetranslator.txt

And is separated into

Result*Resultado* Event*Evento* .... and more 1k++ exapmles like this

Then the process i do is.. I open a 3rd tab... copy an text from the internet.. and place into that tab.. then i run the script by pressing plugin/python script/portuguesetranslator

And its run in my entire document and search and replace ..

So what im doing wrong?

Upvotes: 1

Views: 2188

Answers (2)

reubenb87
reubenb87

Reputation: 303

The answer from @JoshG79 didn't quite work for me (N++ 7.5.1), only the last line needed to be modified:

with open('C:\Users\Administrator\Desktop\IPL\WIP\EnergyTagSubstitutions.txt') as f: for l in f: s = l.split() editor.rereplace(r'\b' + s[0] + r'\b', s[1])

Upvotes: 0

JoshG79
JoshG79

Reputation: 1687

Try regular expressions. \b is the word boundary command in a regular expression. It means that at that point in the regular expression, you must be on a word boundary (not in the middle of a word). You can wrap this around your s[0]:

import re
with open('C:/Users/User/Desktop/Portuguesetranslator.txt') as f:
    for l in f:
        s = l.split('*')
        editor = re.sub(r'\b' + s[0] + r'\b', s[1], editor)

Edit - for notepad++, it looks like you want the last line to be this:

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

Upvotes: 1

Related Questions