from more_itertools import peekable import re class ArbitraryParser: """Matches command strings with %s in them denoting arbitrary phrases""" def __init__(self): self.all_words = [] self.all_words.append("amazing") self.all_words.append("this") self.all_words.append("is") self.all_words.append("a") self.all_words.append("test") self.all_words.append("of") self.all_words.append("pollyana") self.all_words.append("voice") self.all_words.append("typing") self.all_words.append("fuck") self.all_words.append("yeah") def match(self, command, text_line): """ Determine whether a line of input text matches a command that has %s in it. Commands without %s may be passed, and will never match. Returns None if no match, or a list of the words that matched the %s if one was found. Only a single %s is supported and it must be at the end of the command. """ command_words = re.split(r'[,\s-]+', command.strip()) text_words = re.split(r'[,\s-]+', text_line.strip()) text_iter = peekable(text_words) for word in command_words: is_text_end = text_iter.peek(default=None) == None if word == '%s': if not is_text_end: return list(text_iter) else: return None elif is_text_end or word != next(text_iter): return None return None