我的示例代碼是用含有多種報表打印文件,Python的正則表達式搜索和替換所有打印語句
def get_address(cls,latitude,longitude):
try:
geolocator = GoogleV3()
location = geolocator.reverse(latitude,longitude)
print location
print location.address
print "location"
print("location")
return (location.address)
except Exception as e:
print e
正在使用正則表達式從這個代碼刪除所有的print語句(除了打印E), 我的代碼:
import re
regex = r"print[/s]?[^e]?(.)+"
try:
print (re.sub(regex, "AA", str))
except Exception as e:
print e
old_file=open("views.py")
new_file=open("new_text.py", "w")
for line in old_file:
new_line = re.sub(regex, "", line)
new_file.write(new_line)
old_file.close()
new_file.close()
我的代碼寫在views.py,在new_text.py一個新的代碼,運行此腳本後,打印E異常也被刪除,導致語法錯誤。有沒有什麼好的方法可以刪除除print e以外的所有打印語句並將代碼保存在同一個文件中。
不要推倒重來。使用與Python安裝捆綁的[2to3](https://docs.python.org/2/library/2to3.html),將您的代碼更新到Python 3. –
@AryaMcCarthy。這看起來並不相關,因爲OP希望在代碼中保留'print e'。 – ekhumoro