Python: Natural Language Toolkit - Exercises, Solutions

Python NLTK

NLTK is a leading platform for building Python programs to work with human language data. It provides easy-to-use interfaces to over 50 corpora and lexical resources such as WordNet, along with a suite of text processing libraries for classification, tokenization, stemming, tagging, parsing, and semantic reasoning, wrappers for industrial-strength NLP libraries.

The best way we learn anything is by practice and exercise questions. We have started this section for those (beginner to intermediate) who are familiar with Python, Natural Language Toolkit.

Hope, these exercises help you to improve your Python-NLTK coding skills. Currently, following sections are available, we are working hard to add more exercises .... Happy Coding!

List of Python NLTK Exercises :

Installing NLTK:

NLTK requires Python versions 2.7, 3.5, 3.6, or 3.7


  • Install NLTK: run sudo pip install -U nltk
  • Install Numpy (optional): run sudo pip install -U numpy
  • Test installation: run python then type import nltk


These instructions assume that you do not already have Python installed on your machine.

  • Install Python 3.7: http://www.python.org/downloads
  • Install Numpy (optional): https://www.scipy.org/scipylib/download.html
  • Install NLTK: http://pypi.python.org/pypi/nltk
  • Test installation: Start>Python37, then type import nltk

anaconda / packages / nltk 3.4.1 Installers:

conda install 
  •  linux-ppc64le  v3.4.1
  •  osx-32  v3.0.4
  •  linux-64  v3.4.1
  •  win-32  v3.4.1
  •  osx-64  v3.4.1
  •  linux-32  v3.4
  •  win-64  v3.4.1

To install this package with conda run:

  conda install -c anaconda nltk 

[ Want to contribute to Python exercises? Send your code (attached with a .zip file) to us at w3resource[at]yahoo[dot]com. Please avoid copyrighted materials.]

Python: Tips of the Day

Getting the last element of a list:

some_list[-1] is the shortest and most Pythonic.

In fact, you can do much more with this syntax. The some_list[-n] syntax gets the nth-to-last element. So some_list[-1] gets the last element, some_list[-2] gets the second to last, etc, all the way down to some_list[-len(some_list)], which gives you the first element.

You can also set list elements in this way. For instance:

>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]

Note that getting a list item by index will raise an IndexError if the expected item doesn't exist. This means that some_list[-1] will raise an exception if some_list is empty, because an empty list can't have a last element.

Ref: https://bit.ly/3d8TfFP