首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python regex搜索和替换所有print语句

Python regex搜索和替换所有print语句
EN

Stack Overflow用户
提问于 2017-09-03 15:31:02
回答 2查看 1.1K关注 0票数 1

我的示例代码是在一个包含多个打印语句的文件中编写的,

代码语言:javascript
复制
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除外),我的代码:

代码语言:javascript
复制
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、和保存在同一个文件中的代码外,是否有任何好的方法删除所有打印语句。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-09-03 15:40:20

你可以用负的前瞻性模式来实现这一点。将模式更改为

代码语言:javascript
复制
print[/s]?(?! e)(.)+

就能完成任务了。(?!) -是负前瞻性断言,只有当下一个字符不匹配时才匹配。

例如,

代码语言:javascript
复制
>>> p = re.compile('print[/s]?(?! e)(.)+')
>>> 
>>> re.match(p, 'print abc')
<_sre.SRE_Match object at 0x028745E0>
>>> re.match(p, 'print e')
>>> 

如果要支持多个e,可以将其定义为:

代码语言:javascript
复制
>>> 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)。你可以把它换成你想要的任何东西。

票数 3
EN

Stack Overflow用户

发布于 2017-09-04 00:25:58

由于只有三个例外,一个简单的解决方案是跳过它们:

代码语言:javascript
复制
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)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46024995

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档