2017-09-03 12 views
0

我的示例代碼是用含有多種報表打印文件,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以外的所有打印語句並將代碼保存在同一個文件中。

+0

不要推倒重來。使用與Python安裝捆綁的[2to3](https://docs.python.org/2/library/2to3.html),將您的代碼更新到Python 3. –

+0

@AryaMcCarthy。這看起來並不相關,因爲OP希望在代碼中保留'print e'。 – ekhumoro

回答

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') 
>>> 

如果你想支持多個電子郵件的,你可以按照如下定義它:

>>> 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)。您可以將其更改爲任何您想要的數字。

+0

謝謝,但這不適用於所有情況,不適用於打印ee –

+1

@GauravRathore呃,如果您還想保留'print ee',您需要編輯您的問題並準確解釋您想要刪除和保留的內容。 –

+0

您想要覆蓋多少種'print e'?兩個e?三個E的?無窮? – Vinny

1

由於只有三個例外,一個簡單的解決方案是跳過它們:

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) 
相關問題