1
2
3
4
5
6
7
8
9
10
11 """
12 A class for simple chatbots. These perform simple pattern matching on sentences
13 typed by users, and respond with automatically generated sentences.
14
15 These chatbots may not work using the windows command line or the
16 windows IDLE GUI.
17 """
18
19 import string
20 import re
21 import random
22
23 reflections = {
24 "am" : "are",
25 "was" : "were",
26 "i" : "you",
27 "i'd" : "you would",
28 "i've" : "you have",
29 "i'll" : "you will",
30 "my" : "your",
31 "are" : "am",
32 "you've" : "I have",
33 "you'll" : "I will",
34 "your" : "my",
35 "yours" : "mine",
36 "you" : "me",
37 "me" : "you"
38 }
39
41 - def __init__(self, pairs, reflections={}):
42 """
43 Initialize the chatbot. Pairs is a list of patterns and responses. Each
44 pattern is a regular expression matching the user's statement or question,
45 e.g. r'I like (.*)'. For each such pattern a list of possible responses
46 is given, e.g. ['Why do you like %1', 'Did you ever dislike %1']. Material
47 which is matched by parenthesized sections of the patterns (e.g. .*) is mapped to
48 the numbered positions in the responses, e.g. %1.
49
50 @type pairs: C{list} of C{tuple}
51 @param pairs: The patterns and responses
52 @type reflections: C{dict}
53 @param reflections: A mapping between first and second person expressions
54 @rtype: C{None}
55 """
56
57 self._pairs = [(re.compile(x, re.IGNORECASE),y) for (x,y) in pairs]
58 self._reflections = reflections
59
60
62 """
63 Substitute words in the string, according to the specified reflections,
64 e.g. "I'm" -> "you are"
65
66 @type str: C{string}
67 @param str: The string to be mapped
68 @rtype: C{string}
69 """
70
71 words = ""
72 for word in string.split(string.lower(str)):
73 if self._reflections.has_key(word):
74 word = self._reflections[word]
75 words += ' ' + word
76 return words
77
87
89 """
90 Generate a response to the user input.
91
92 @type str: C{string}
93 @param str: The string to be mapped
94 @rtype: C{string}
95 """
96
97
98 for (pattern, response) in self._pairs:
99 match = pattern.match(str)
100
101
102 if match:
103 resp = random.choice(response)
104 resp = self._wildcards(resp, match)
105
106
107 if resp[-2:] == '?.': resp = resp[:-2] + '.'
108 if resp[-2:] == '??': resp = resp[:-2] + '?'
109 return resp
110
111
112
123