我的示例代码是在一个包含多个打印语句的文件中编写的,
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正在使用regex删除此代码中的所有打印语句(打印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异常也被删除,这会导致语法错误。除了、打印e、和保存在同一个文件中的代码外,是否有任何好的方法删除所有打印语句。
发布于 2017-09-03 15:40:20
你可以用负的前瞻性模式来实现这一点。将模式更改为
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')这将匹配1到5倍的e(打印eeeee)。你可以把它换成你想要的任何东西。
发布于 2017-09-04 00:25:58
由于只有三个例外,一个简单的解决方案是跳过它们:
allowed_prints = ['print(e)', 'print (e)', 'print e']
for line in old_file:
stripped = line.strip()
# or, if you want to account for comments in the print line:
# stripped = line.split('#')[0].strip()
if stripped.startswith('print') and stripped not in allowed_prints:
continue
new_file.write(line)https://stackoverflow.com/questions/46024995
复制相似问题