Search code examples
pythonnltkcherrypy

CherryPy WebService not returning NLTK collocations to browser window


I have a very simple CherryPy webservice that I hope will be the foundation of a larger project, however, I need to get NLTK to work the way I want.

My python script imports NLTK and uses the collocation (bigram) function of NLTK, to do some analysis on pre-loaded data.

I have a couple of questions:

1) Why is the program not returning the collocations to my browser, but only to my console?.

2) Why if I am specifying from nltk.book import text4, the program imports the whole set of sample books (text1 to text9)?

Please, keep in mind that I am a newbie, so the answer might be in front of me, but I don't see it.

Main question: How do I pass the collocation results to the browser (webservice), instead of console?

Thanks

import cherrypy
import nltk
from nltk.book import text4

class BiGrams:
    def index(self):
        return text4.collocations(num=20)
    index.exposed = True

cherrypy.quickstart(BiGrams())

Solution

  • My guess is that what you get back from the collocations() call is not a string, and that you need to serialize it. Try this instead:

    import cherrypy
    import nltk
    from nltk.book import text4
    import simplejson
    
    class BiGrams:
        def index(self):
            c = text4.collocations(num=20)
            return simplejson.dumps(c)
        index.exposed = True
    
    cherrypy.quickstart(BiGrams())