2011-11-01 99 views
-2

我使用以下監聽器來聆聽特定模式。我希望在發送給它的數據中找到「hello」。該過程方法每秒鐘被調用多次,因此不知道如何在不斷增長的列表中保存所有處理的數據(全部)。有沒有更好的方法來做到這一點?聆聽特定模式

class Listener: 
    def __init__(self, data_to_catch): 
     self.data_to_catch = data_to_catch 
     self.length_of_data_to_catch = len(data_to_catch) 
     self.previous_data = "" 
     self.found = False 

    def process(self, data): 
     if self.found: 
      return 

     self.previous_data = self.previous_data + data 
     if not self.data_to_catch in self.previous_data: 
      # see if some of the data to catch has arrived, if so keep it     
      for i in reversed(range(min(self.length_of_data_to_catch,len(self.previous_data)))): 
       if self.data_to_catch[:i+1] == self.previous_data[-i-1:]: 
        return 
      else: 
       self.previous_data = "" 
       return 

     self.found = True 
     print("found!") 

l = Listener("hello") 
l.process("he") 
l.process("llh") 
l.process("e") 
l.process("ll") 
l.process("he") 
l.process("llohe") 
+0

以asp.net作爲標題入門,沒有asp.net。 - 經典 – JonH

+0

:)標題從我開始寫的最後一個問題保存下來...現在修復它。 – Baz

回答

1

也許是這樣的:

class Listener: 
    def __init__(self, data_to_catch): 
     self.data_to_catch = data_to_catch 
     self.data = "" 
     self.found = False 
     self.pos = 0 

    def process(self, data): 
     if self.found: 
      return 

     self.data += data 
     self.found = self.data_to_catch in self.data[self.pos:] 
     self.pos = max(0, len(self.data) - len(self.data_to_catch)) 

     if self.found: 
      print "found!" 

l = Listener("hello") 
l.process("he") 
l.process("llh") 
l.process("e") 
l.process("ll") 
l.process("he") 
l.process("llohe") 

雖然,你是說(我錯過了原本),你想保持的self.data小的長度。在這種情況下,您可以執行以下操作:

def process(self, data): 
     if self.found: 
      return 

     self.data += data 
     self.found = self.data_to_catch in self.data 

     pos = max(0, len(self.data) - len(self.data_to_catch)) 
     self.data = self.data[pos:] 

     if self.found: 
      print "found!" 
+0

非常好,謝謝! – Baz