我使用以下侦听器来侦听特定模式。我希望在发送给它的数据中找到“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 :(得分: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!"