# Reads and writes to MontyLingua. # (Put this file and subbot.org/montylingua/MontyLingua2.py # in the MontyLingua directory.) class MontyLingua def initialize @monty = IO.popen("python MontyLingua2.py", "r+") 16.times { |i| # Read the lines preceding the first prompt line = @monty.gets puts line } end def putstr(s = '') s.strip! @monty.puts s getstr end def getResponse(s = '') return putstr(s) end def getstr full_response = "" @monty.gets # skip over two blank lines @monty.gets while (line = @monty.gets) =~ /^.*/ full_response << line << " " c = @monty.getc # Check the first character of the next line if c == nil then break end if c.chr == ">" then break end # If it's the first chr of a prompt, break @monty.ungetc(c) #If it's not a prompt, push the chr back on the stream. end return full_response end # Try to find the subject. def getSubject(input = '') if input =~ /^In (?:.*?), (.*)/i #puts $1 return getSubject($1) end parse = getResponse(input) arr = parse.split("\n") constituents = arr[0] if constituents =~ /\(NX (.*?) NX\)/ subject = postprocess $1.to_s return "#{subject}" end return "I don't know what the subject in #{input} is." end # Try to get the main verb. def getVerb(input = '') parse = getResponse(input) constituents = parse.split("\n")[0] if constituents =~ /\(VX (.*?) VX\)/ verb = postprocess $1.to_s return verb end return "I don't know what the verb in #{input} is." end # Try to get the object. def getObject(input = '') parse = getResponse(input) constituents = parse.split("\n")[0] if constituents =~ /VX\) .*?\(NX (.*?) NX\)/ object = postprocess $1.to_s return object end return "I don't know what the object in #{input} is." end # Return the constituent tree. def getConstituents(input = '') parse = getResponse(input) return parse.split("\n")[0] end # Strip tags from MontyLingua's output. def postprocess(phrase = '') if phrase == '' then return '' end phrase.gsub!(/\/[A-Z]*/, '') return phrase end end if $0 == __FILE__ monty = MontyLingua.new print "\n> "; $stdout.flush quitwords = [":q", "quit", "bye", "exit"] while (line = gets) !~ /^(#{quitwords.join('|')})+/ and line !~ /^$/ line.chomp! puts puts monty.getSubject(line) puts monty.getVerb(line) puts monty.getObject(line) #puts monty.getConstituents(line) print "\n> "; $stdout.flush end print "Bye!" end