我的示例代码写在一个包含多个打印语句的文件中,
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
我正在使用正则表达式从此代码中删除所有打印语句(打印 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中,运行这个脚本后,print e in exception也被删除了,导致语法错误。有什么好的方法可以删除除 print e 之外的所有打印语句并将代码保存在同一文件中。
最佳答案
您可以使用负先行模式来做到这一点。将模式更改为
print[/s]?(?! e)(.)+
会做的工作。 (?!)
- 是否定先行断言,仅当下一个字符不匹配时才匹配
例如,
>>> p = re.compile('print[/s]?(?! e)(.)+')
>>>
>>> re.match(p, 'print abc')
<_sre.SRE_Match object at 0x028745E0>
>>> re.match(p, 'print e')
>>>
如果要支持多个e,可以这样定义:
>>> re.match('print (?!e{1,5}$)\D+', 'print ele')
<_sre.SRE_Match object at 0x00000000042904A8>
>>> re.match('print (?!e{1,5}$)\D+', 'print ee')
>>> re.match('print (?!e{1,5}$)\D+', 'print eee')
这将匹配 e 的 1 到 5 次(打印 eeeee)。您可以将其更改为您想要的任何数字。
关于Python正则表达式搜索并替换所有打印语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46024995/