rules = [ (r"I feel (.*)", "Why do you feel {}?"),
(r"I need (.*)", "Why do you need {}?"),
(r"My (.*)", "Tell me more about your {}."),
(r".*", "Please go on.") ]
while True: text = input("You: ")
if text == "quit": break
for pattern, reply in rules: m = re.match(pattern, text, re.I) if m: if m.groups(): print("ELIZA:", reply.format(m.group(1))) else: print("ELIZA:", reply) break
运行效果:
1 2 3 4 5 6 7 8
You: I feel tired ELIZA: Why do you feel tired?
You: My father is strict ELIZA: Tell me more about your father is strict.