###用正则表达式将python 2.7的print “ ”格式替换成python 3的 print() 格式
最近碰到一段用python 2.7写的代码,代现在的机器上安装的都是python 3,自己重写代码太麻烦,所以把旧代码改造一下,python2.7的print格式与新版本的python 3完全不同,所以想到用python强大的正则表达式来解决这个问题!
代码如下
import sys
import re
infile=open('mycode.py','r',encoding = 'utf-8')
outfile=open('outfile.txt','w')
for sline in infile.readlines()[1:]:
matched = 0
batRegex = re.compile(r'(.*)print(.*)$')
matched = batRegex.match(sline)
if matched:
newLine = re.sub(r'print.*$',"print("+matched.group(2)+")",sline)
outfile.write(newLine)
else:
outfile.write(sline)
infile.close()
outfile.close()
input('Press Enter\n')