nltk / nltk_book

NLTK Book
http://www.nltk.org/book
403 stars 143 forks source link

Chapter 4: update Python 2 example for module file location #229

Open pjhinton opened 4 years ago

pjhinton commented 4 years ago

In section 4.6, there is the following example:

>>> nltk.metrics.distance.__file__
'/usr/lib/python2.5/site-packages/nltk/metrics/distance.pyc'

This fails with Python 3.7.4.

>>> nltk.metrics.distance.__file__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'nltk' is not defined

Attempts to import and then expose fail as well:

>>> import nltk.metrics.distance
>>> nltk.metrics.distance.__file__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'nltk.translate.metrics' has no attribute 'distance'

This code does produce a result:

>>> from nltk.metrics import distance
>>> distance.__file__
'/home/pj/.pyenv/versions/nltkbook/lib/python3.7/site-packages/nltk/metrics/distance.py'
>>> quit()

The reason for this behavior may be a side effect of this import in nltk/__init__.py

from nltk.translate import *

which brings nltk.translate.metrics in as nltk.metrics.

>>> import nltk
>>> nltk.metrics
<module 'nltk.translate.metrics' from '/home/pj/.pyenv/versions/nltkbook/lib/python3.7/site-packages/nltk/translate/metrics.py'>
>>> nltk.metrics.__file__
'/home/pj/.pyenv/versions/nltkbook/lib/python3.7/site-packages/nltk/translate/metrics.py'