X-Git-Url: http://gitweb.pimeys.fr/?a=blobdiff_plain;f=quotes.py;h=fa9ac0afdedf3c8dfc6b945150d46533b4b03f72;hb=e40da5a33f6a26bc6524bad637483db3fe602cd1;hp=35f486081a546736312b68d0bd082362050ed097;hpb=6d6af879045f6c8314a1cc6909b74ede71215e65;p=bots%2Fparrot.git diff --git a/quotes.py b/quotes.py index 35f4860..fa9ac0a 100644 --- a/quotes.py +++ b/quotes.py @@ -11,6 +11,9 @@ import random import config +quote_matcher = re.compile(config.quote_regexp, flags=re.UNICODE) +quote_matcher_with_timestamp = re.compile(config.quote_regexp_with_timestamp, flags=re.UNICODE) + def get_now(): """ Renvoie la date actuelle """ return datetime.datetime(*time.localtime()[:6]) @@ -42,7 +45,6 @@ class Quote(object): Indépendamment de la date. """ return [self.author, self.content] == [otherquote.author, otherquote.content] -quote_matcher = re.compile(config.quote_regexp) def parse(text, date=None): """ Parse le ``text`` et renvoie une quote ou None. """ @@ -97,6 +99,37 @@ class QuoteDB(object): def randomfrom(self, author): """ Sort une quote aléatoire de ``author`` """ return random.choice([q for q in self.quotelist if q.author == author]) + + def search(self, inquote=None, author=None, regexp=False): + """Fait une recherche dans les quotes.""" + if regexp: + if inquote is None: + inquote = ".*" + if author is None: + author = ".*" + qreg = re.compile(inquote, flags=re.UNICODE) + areg = re.compile(author, flags=re.UNICODE) + l = [q for q in self.quotelist if qreg.match(q.content) and areg.match(q.author)] + else: + if inquote is None: + inquote = "" + if author is None: + author = "" + l = [q for q in self.quotelist if inquote in q.content and author in q.author] + return l + + def search_authors(self, author=None, regexp=False): + """Renvoie la liste des auteurs contenant ``author`` ou qui matchent la regexp.""" + if regexp: + if author is None: + author = ".*" + areg = re.compile(author, flags=re.UNICODE) + l = list(set([q.author for q in self.quotelist if areg.match(q.author)])) + else: + if author is None: + author = "" + l = list(set([q.author for q in self.quotelist if author in q.author])) + return l def dump(quotedb, dump_file=None): """Pour exporter les quotes dans un format readable vers un fichier.""" @@ -113,8 +146,7 @@ def restore(dump_file=None): with open(dump_file) as f: t = f.read() t = t.decode("utf-8") # Oui, ça peut fail, mais on ne doit alors pas continuer - regex = re.compile(config.quote_regexp_with_timestamp) - l = [m.groupdict() for m in regex.finditer(t)] + l = [m.groupdict() for m in quote_matcher_with_timestamp.finditer(t)] # On instancie les quotes grâce aux dicos qui ont déjà la bonne tronche l = [Quote(**q) for q in l] newquotedb = QuoteDB()