Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a python script to query MIT START website from local machine

Tags:

python

I'm learning Python and the project I've currently set myself includes sending a question from my laptop connected to the net, connect to the MIT START NLP database, enter the question, retrieve the response and display the response. I've read through the "HOWTO Fetch Internet Resources Using urllib2" at docs.python.org but I seem to be missing some poignant bit of this idea. Here's my code:

import urllib
import urllib2

question = raw_input("What is your question? ")

url = 'http://start.csail.mit.edu/'
values = question

data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()

print the_page

and here's the error I'm getting:

Traceback (most recent call last): File "mitstart.py", line 9, in data = urllib.urlencode(values) File "/usr/lib/python2.7/urllib.py", line 1298, in urlencode raise TypeError TypeError: not a valid non-string sequence or mapping object

So I'm thinking that the way I set question in vales was wrong, so I did

values = {question}

and values = (question)

and values = ('question')

with no joy.

(I know, and my response is "I'm learning, it's late, and suddenly my wife decided she needed to talk to me about something trivial while I was trying to figure this out)

Can I get some guidance or at least get pointed in the right direction?

like image 835
richard Avatar asked Feb 22 '26 07:02

richard


1 Answers

Note that your error says: TypeError: not a valid non-string sequence or mapping object

So, while you've created values as a string, you need a non-string sequence or a mapping object.

urlencoding requires key value pairs (e.g. a mapping object or a dict), so you generally pass it a dictionary.

Looking at the source for the form, you'll see:

<input type="text" name="query" size="60">

This means you should create a dict, something like:

values = { 'query': 'What is your question?' }

Then you should be able to pass that as the argument to urlencode().

like image 95
ernie Avatar answered Feb 24 '26 21:02

ernie