2013-07-15 31 views
1

我試圖檢查是否在打開的文檔的特定行上執行了正則表達式,然後如果是這樣,則將計數變量加1到 。如果計數超過2我希望它停止。下面的代碼是我到目前爲止。如何檢查是否執行了Python中的RE

for line in book: 
    if count<=2: 
      reg1 = re.sub(r'Some RE',r'Replaced with..',line) 
      f.write(reg1) 
      "if reg1 was Performed add to count variable by 1" 

回答

0

你可以把它比作原始的字符串,看它是否改變了:

for line in book: 
    if count<=2: 
     reg1 = re.sub(r'Some RE',r'Replaced with..',line) 
     f.write(reg1) 
     if line != reg1: 
      count += 1 
+0

如果if語句沒有在該行上執行,那麼if語句會是什麼樣子? –

+0

...'!='(不等於)是什麼?當然是==(等於)。 – kindall

+0

它只是不會增加計數器,因爲'line'和'reg1'會相同。如果沒有匹配,'re.sub()'只返回原始字符串。 – Nate

2

如果這個想法是,以確定是否置換,線路上完成,這是相當簡單:

count = 0 
for line in book: 
    if count<=2: 
     reg1 = re.sub(r'Some RE',r'Replaced with..',line) 
     f.write(reg1) 
     count += int(reg1 == line) 
1

您可以將函數傳遞給re.sub作爲替換值。這可以讓你做的東西是這樣的:(雖然一個簡單的搜索,然後子方法而較慢的會更容易推理):

import re 

class Counter(object): 
    def __init__(self, start=0): 
     self.value = start 

    def incr(self): 
     self.value += 1 

book = """This is some long text 
with the text 'Some RE' appearing twice: 
Some RE see? 
""" 

def countRepl(replacement, counter): 
    def replacer(matchobject): 
     counter.incr() 
     return replacement 

    return replacer 

counter = Counter(0) 

print re.sub(r'Some RE', countRepl('Replaced with..', counter), book) 

print counter.value 

這將產生以下的輸出:

This is some long text 
with the text 'Replaced with..' appearing twice: 
Replaced with.. see? 

2 
4

絕對是最好的方法這樣做的,這是使用re.subn()代替re.sub()

re.subn()返回一個元組(new_string, number_of_changes_made)所以它適合你:

for line in book: 
    if count<=2: 
     reg1, num_of_changes = re.subn(r'Some RE',r'Replaced with..',line) 
     f.write(reg1) 
     if num_of_changes > 0: 
      count += 1 
0

subn會告訴你在該行中有多少個替換,並且count參數將限制將要嘗試的替換次數。將它們放在一起,即使在一行代碼中有多個子代碼,代碼也會在兩次替換後停止。

look_count = 2 
for line in book: 
    reg1, sub_count = re.subn(r'Some RE', r'Replaced with..', line,count=look_count) 
    f.write(reg1) 
    look_count -= sub_count 
    if not look_count: 
     break 
相關問題