【问题标题】:Python regex search and replace all print statementPython 正则表达式搜索并替换所有打印语句
【发布时间】:2017-09-03 15:31:02
【问题描述】:

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

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也被删除了,导致语法错误。有什么好的方法可以删除除 print e 之外的所有打印语句并将代码保存在同一个文件中。

【问题讨论】:

  • 不要重新发明轮子。使用与 Python 安装捆绑在一起的 2to3 将您的代码更新到 Python 3。
  • @AryaMcCarthy。这似乎无关紧要,因为 OP 希望在代码中保留 print e。

标签: python regex file


【解决方案1】:

您可以使用负前瞻模式来做到这一点。将您的模式更改为

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)。您可以将其更改为您想要的任何数字。

【讨论】:

  • 谢谢,但这不适用于所有情况,不适用于打印 ee
  • @GauravRathore 好吧,如果您还想保留print ee,您需要编辑您的问题并准确说明您要删除和保留的内容。
  • 您想覆盖print e 的多少种变体?两个e?三个e?无穷大?
  • @GauravRathore 我添加了另一个解决方案,以匹配多个 e 作为变量
  • 感谢 Vinny,您之前的代码可以正常工作,但还有一个复杂的问题,我也想忽略 print(e)、print (e) 和 print e,但不要忽略 print ee 或 print 'e '。替换除 print(e)、print (e) 和 print e 之外的所有内容
【解决方案2】:

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

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 2014-08-16
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    相关资源
    最近更新 更多