Poodletooth-iLand/otp/chat/WhiteList.py

47 lines
1.4 KiB
Python
Raw Normal View History

2015-03-03 22:10:12 +00:00
from bisect import bisect_left
2015-03-31 11:59:36 +00:00
2015-04-01 11:39:59 +00:00
class WhiteList:
2015-05-30 18:50:36 +00:00
def setWords(self, words):
self.words = words
2015-03-03 22:10:12 +00:00
self.numWords = len(self.words)
def cleanText(self, text):
2015-05-30 18:50:36 +00:00
return text.strip('.,?!').lower()
2015-03-03 22:10:12 +00:00
def isWord(self, text):
return self.cleanText(text) in self.words
2015-03-03 22:10:12 +00:00
def isPrefix(self, text):
text = self.cleanText(text)
i = bisect_left(self.words, text)
2015-05-30 18:50:36 +00:00
return i != self.numWords and self.words[i].startswith(text)
def getReplacement(self, text, av=None, garbler=None):
2015-05-30 19:02:08 +00:00
return '\x01WLRed\x01%s\x02' % text if not garbler else garbler.garble(av, text)
2015-03-03 22:10:12 +00:00
2015-05-30 18:50:36 +00:00
def processText(self, text, av=None, garbler=None):
if (not self.words) or (text.startswith('~') and not garbler):
2015-05-30 18:50:36 +00:00
return text
2015-04-02 12:23:24 +00:00
2015-05-30 18:50:36 +00:00
words = text.split(' ')
newWords = []
2015-04-02 12:23:24 +00:00
2015-05-30 18:50:36 +00:00
for word in words:
if (not word) or self.isWord(word):
newWords.append(word)
else:
newWords.append(self.getReplacement(word, av, garbler))
2015-04-02 12:23:24 +00:00
2015-05-30 18:50:36 +00:00
lastWord = words[-1]
if (not lastWord) or self.isPrefix(lastWord):
newWords[-1] = lastWord
else:
newWords[-1] = self.getReplacement(lastWord, av, garbler)
2015-04-02 12:23:24 +00:00
2015-05-30 18:50:36 +00:00
return ' '.join(newWords)
def processThroughAll(self, text, av=None, garbler=None):
return self.processText(text, av, garbler)