Home > OS >  How do I put a pair of parentheses on each matched line with Python regex?
How do I put a pair of parentheses on each matched line with Python regex?

Time:12-25

I'm trying to convert the following code

print "*** Dictionaries"
dictionaries = json.loads(api.getDictionaries())
print dictionaries
...
print(bestMatch)
...

to

print("*** Dictionaries")
dictionaries = json.loads(api.getDictionaries())
print(dictionaries)
...
print(bestMatch)
...

that is, to put a pair of parentheses on each print line.

Here is my code

import re

with open('p2code.txt') as f:
  lines = [line.rstrip() for line in f]

cmplr = re.compile(r'(?<=print).*')

p3code = []

for line in lines:
  p3line = line
  m = cmplr.search(line)
  if m:
    p3line = 'print('   m.group(0)   ')'
  p3code.append(p3line)

with open('p3code.txt', 'w') as f:
  for line in p3code:
    f.write(f"{line}\n")

There're 2 questions related to the code above.

Is there a more elegant way to do the replacement, e.g. cmplr.sub? If yes, how do I do that?

one of the print lines has already put the parentheses

print(bestMatch)

How do I make my code skip that line, avoiding something like

print((bestMatch))

The idea/need comes from Cambridge's API doc https://dictionary-api.cambridge.org/api/resources#python

CodePudding user response:

You can just do it with a single command at the command line using sed. Something like:

sed -i -E 's/print ([^\(].*[^\)])/print\(\1\)/g' code.py

This is both minimal and easy. But in case you're pressed on doing it with python, you can make use of the following:

re.sub("print ([^\(].*[^\)])", r"print($\1)", lineOfFile)

You can play with the regex further here.

  • Related