summary refs log tree commit diff
path: root/src/pollyanna/arbitrary.py
blob: fbaba4c87ec4776c31fed0d1359619856f86cb35 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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