问题
I have a Python script which reads data from a database into a list and fills a template. The database structure changed so now I have to add 2 to all indexes. Is there a way to do such thing using notepad++?
What I have is something like:
cursor.execute("SELECT * FROM mytable WHERE id = %s",id)
row = cursor.fetchone()
nameSpace = {'valone':str(row[1]),'valtwo':str(row[2]),'valthree':str(row[3]),} #and so on
And I need it to be:
cursor.execute("SELECT * FROM mytable WHERE id = %s",id)
row = cursor.fetchone()
nameSpace = {'valone':str(row[3]),'valtwo':str(row[4]),'valthree':str(row[5]),} #and so on
There's over a hundred variables, so I don't want to do it manually.
Thanks in advance ;)
回答1:
You may use a simple regex like \w+\[([0-9]+)] and use a PythonScript to process these matches, incrementing the number inside Group 1.
- Install PythonScript
- Go to Plugins -> Python Script -> New Script
- Create a new
increment_numbers_2up.pyscript - Add this contents:
def increment_2_up(match):
return '%s%s]'%(match.group(1), str(int(match.group(2))+2))
editor.rereplace(r'(\w+\[)([0-9]+)]', increment_2_up)
Now, run the script from Plugins -> Python Script -> Scripts -> increment_numbers_2up
I got this result: nameSpace = {'valone':str(row[3]),'valtwo':str(row[4]),'valthree':str(row[5]),} #and so on
Pattern details:
(\w+\[)- Group 1 capturing 1+ word chars ([a-zA-Z0-9_]) and a[([0-9]+)- Group 2 capturing 1+ digits]- a literal closing]bracket.
The Python code here - str(int(match.group(2))+2) - parses the digits captured into Group 2 with int(match.group(2), then adds 2, and casts the value to a string with str().
来源:https://stackoverflow.com/questions/38664254/modify-indexes-in-python-script-using-notepad