
NLTK ANALYZER



What is a text? At one level, it is a sequence of symbols on a page such as this one. At
another level, it is a sequence of chapters, made up of a sequence of sections, where
each section is a sequence of paragraphs, and so on. However, for our purposes, we
will think of a text as nothing more than a sequence of words and punctuation. Hereâs
how we represent text in Python, in this case the opening sentence of Moby Dick:
>>>sent1 = [‘Call’, ‘me’, ‘Ishmael’, ‘.’]
>>>

The most obvious fact about texts that emerges from the preceding examples is that
they differ in the vocabulary they use. In this section, we will see how to use the com
puter to count the words in a text in a variety of useful ways. As before, you will jump
right in and experiment with the Python interpreter, even though you may not have
studied Python systematically yet. Test your understanding by modifying the examples,
and trying the exercises at the end of the chapter.
Letâs begin by finding out the length of a text from start to finish, in terms of the words
and punctuation symbols that appear. We use the term len to get the length of some
thing, which weâll apply here to the book of Genesis:
>>>len(text3)
44764
>>>

There are many ways to examine the context of a text apart from simply reading it. A
concordance view shows us every occurrence of a given word, together with some
context. Here we look up the word monstrous in Moby Dick by entering text1 followed
by a period, then the term concordance, and then placing “monstrous” in parentheses:
>>>text1.concordance(“monstrous”)
Building index…
Displaying 11 of 11 matches:
ong the former , one was of a most monstrous size . … This came towards us ,
ON OF THE PSALMS . ” Touching that monstrous bulk of the whale or ork we have r
ll over with a heathenish array of monstrous clubs and spears . Some were thick
d as you gazed , and wondered what monstrous cannibal and savage could ever hav
that has survived the flood ; most monstrous and most mountainous ! That Himmal
they might scout at Moby Dick as a monstrous fable , or still worse and more de
th of Radney .'” CHAPTER 55 Of the monstrous Pictures of Whales . I shall ere l
ing Scenes . In connexion with the monstrous pictures of whales , I am strongly
ere to enter upon those still more monstrous stories of them which are to be fo
ght have been rummaged out of this monstrous cabinet there is no telling . But
of Whale – Bones ; for Whales of a monstrous size are oftentimes cast up dead u
>>>

Getting Started with Python
One of the friendly things about Python is that it allows you to type directly into the
interactive interpreterâthe program that will be running your Python programs. You
can access the Python interpreter using a simple graphical interface called the In
teractive DeveLopment Environment (IDLE). On a Mac you can find this under Ap
plicationsâMacPython, and on Windows under All ProgramsâPython. Under Unix
you can run Python from the shell by typing idle (if this is not installed, try typing
python). The interpreter will print a blurb about your Python version; simply check that
you are running Python 2.4 or 2.5 (here it is 2.5.1):
Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type “help”, “copyright”, “credits” or “license” for more information.
>>>

So far, when we have wanted to look at the contents of a variable or see the result of a
calculation, we have just typed the variable name into the interpreter. We can also see
the contents of a variable using the print statement:
>>>print monty
Monty Python
Notice that there are no quotation marks this time. When we inspect a variable by
typing its name in the interpreter, the interpreter prints the Python representation of
its value. Since itâs a string, the result is quoted. However, when we tell the interpreter
to print the contents of the variable, we donât see quotation characters, since there are
none inside the string.
The print statement allows us to display more than one item on a line in various ways,
as shown here:
>>>grail = ‘Holy Grail’
>>>print monty + grail
Monty PythonHoly Grail
>>>print monty, grail
Monty Python Holy Grail
>>>print monty, “and the”, grail
Monty Python and the Holy Grail

Sometimes we want to capture the text that a user inputs when she is interacting with
our program. To prompt the user to type a line of input, call the Python function
raw_input(). After saving the input to a variable, we can manipulate it just as we have
done for other strings.
>>>s = raw_input(“Enter some text: “)
Enter some text: On an exceptionally hot evening early in July
>>>print “You typed”, len(nltk.word_tokenize(s)), “words.”
You typed 8 words.

The blogosphere is an important source of text, in both formal and informal registers. With the help of a third-party Python library called the Universal Feed Parser, freely downloadable from http://feedparser.org/, we can access the content of a blog, as shown here:
>>> import feedparser
>>> llog = feedparser.parse(“http://languagelog.ldc.upenn.edu/nll/?feed=atom”)
>>> llog[‘feed’][‘title’] u’Language Log’
>>> len(llog.entries) 15
>>> post = llog.entries[2]
>>> post.title u”He’s My BF”
>>> content = post.content[0].value
>>> content[:70]
u’Today I was chatting with three of our visiting graduate students f’
>>> nltk.word_tokenize(nltk.html_clean(content))
>>> nltk.word_tokenize(nltk.clean_html(llog.entries[2].content[0].value))
[u’Today’, u’I’, u’was’, u’chatting’, u’with’, u’three’, u’of’, u’our’, u’visiting’,
u’graduate’, u’students’, u’from’, u’the’, u’PRC’, u’.’, u’Thinking’, u’that’, u’I’,
u’was’, u’being’, u’au’, u’courant’, u’,’, u’I’, u’mentioned’, u’the’, u’expression’,
u’DUI4XIANG4′, u’\u5c0d\u8c61′, u'(“‘, u’boy’, u’/’, u’girl’, u’friend’, u'”‘, …]

Much of the text on the Web is in the form of HTML documents. You can use a web
browser to save a page as text to a local file, then access this as described in the later
section on files. However, if youâre going to do this often, itâs easiest to get Python to
do the work directly. The first step is the same as before, using urlopen. For fun weâll pick a BBC News story called âBlondes to die out in 200 years,â an urban legend passed
along by the BBC as established scientific fact:
>>>url = “http://news.bbc.co.uk/2/hi/health/2284783.stm“
>>>html = urlopen(url).read()
>>>html[:60]
‘<!doctype html public “-//W3C//DTD HTML 4.0 Transitional//EN’

Electronic Books
A small sample of texts from Project Gutenberg appears in the NLTK corpus collection. However, you may be interested in analyzing other texts from Project Gutenberg. You can browse the catalog of 25,000 free online books at http://www.gutenberg.org/cata log/, and obtain a URL to an ASCII text file. Although 90% of the texts in Project Gutenberg are in English, it includes material in over 50 other languages, including Catalan, Chinese, Dutch, Finnish, French, German, Italian, Portuguese, and Spanish (with more than 100 texts each).
Text number 2554 is an English translation of Crime and Punishment, and we can access it as follows.
>>> from urllib import urlopen
>>> url = “http://www.gutenberg.org/files/2554/2554.txt”
>>> raw = urlopen(url).read()
>>> type(raw)
>>> len(raw) 1176831
>>> raw[:75]
‘The Project Gutenberg EBook of Crime and Punishment, by Fyodor Dostoevsky\r\n’