Python:
import re
import random
class Eliza:
reflections = {
"am": "are"
}
class PhraseMatcher:
def __init__(self, matcher, responses):
self.matcher = re.compile(matcher)
self.responses = responses
def matches(self, str):
return self.matcher.match(str) is not None
def respond(self, str):
m = self.matcher.match(str)
p = self.random_phrase()
for i in range(len(m.groups())):
s = self.reflect(m.group(i + 1))
p = p.replace("{" + str(i) + "}", s)
return p
@staticmethod
def reflect(s):
words = s.split(" ")
for i in range(len(words)):
if words[i] in Eliza.reflections:
words[i] = Eliza.reflections[words[i]]
return " ".join(words)
def random_phrase(self):
return self.responses[abs(random.randint(0, len(self.responses) - 1))]
def __str__(self):
return self.matcher.pattern + ":" + str(self.responses)
babble = [
PhraseMatcher("quit", ["Thank you for talking with me.", "Good-bye.",
"Thank you, that will be $150. Have a good day!"])
]
def respond(self, msg):
for pm in self.babble:
if pm.matches(msg):
return pm.respond(msg.lower())
return ""