Package nltk_lite :: Package chat
[hide private]
[frames] | no frames]

Source Code for Package nltk_lite.chat

  1  # Natural Language Toolkit: Chatbots 
  2  # 
  3  # Copyright (C) 2001-2007 University of Pennsylvania 
  4  # Authors: Steven Bird <sb@csse.unimelb.edu.au> 
  5  # URL: <http://nltk.sf.net> 
  6  # For license information, see LICENSE.TXT 
  7   
  8  # Based on an Eliza implementation by Joe Strout <joe@strout.net>, 
  9  # Jeff Epler <jepler@inetnebr.com> and Jez Higgins <jez@jezuk.co.uk>. 
 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   
40 -class Chat(object):
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 # bug: only permits single word expressions to be mapped
61 - def _substitute(self, str):
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
78 - def _wildcards(self, response, match):
79 pos = string.find(response,'%') 80 while pos >= 0: 81 num = string.atoi(response[pos+1:pos+2]) 82 response = response[:pos] + \ 83 self._substitute(match.group(num)) + \ 84 response[pos+2:] 85 pos = string.find(response,'%') 86 return response
87
88 - def respond(self, str):
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 # check each pattern 98 for (pattern, response) in self._pairs: 99 match = pattern.match(str) 100 101 # did the pattern match? 102 if match: 103 resp = random.choice(response) # pick a random response 104 resp = self._wildcards(resp, match) # process wildcards 105 106 # fix munged punctuation at the end 107 if resp[-2:] == '?.': resp = resp[:-2] + '.' 108 if resp[-2:] == '??': resp = resp[:-2] + '?' 109 return resp
110 111 # Hold a conversation with a chatbot 112
113 -def converse(bot, quit="quit"):
114 input = "" 115 while input != quit: 116 input = quit 117 try: input = raw_input(">") 118 except EOFError: 119 print input 120 if input: 121 while input[-1] in "!.": input = input[:-1] 122 print bot.respond(input)
123