Laila Campos
Laila Campos

Reputation: 801

Remove the initial text when using the nltk.book module in python

I'm learning about NLP and messing around with nltk but just by importing the module on my program, whenever I run the script I get the following text:

*** Introductory Examples for the NLTK Book ***
Loading text1, ..., text9 and sent1, ..., sent9
Type the name of the text or sentence to view it.
Type: 'texts()' or 'sents()' to list the materials.
text1: Moby Dick by Herman Melville 1851
text2: Sense and Sensibility by Jane Austen 1811
text3: The Book of Genesis
text4: Inaugural Address Corpus
text5: Chat Corpus
text6: Monty Python and the Holy Grail
text7: Wall Street Journal
text8: Personals Corpus
text9: The Man Who Was Thursday by G . K . Chesterton 1908

I know it's information about the module, but it's not necessary for me right now. Is there a way to make it so the console doesn't print it when I run the script?

Upvotes: 1

Views: 224

Answers (1)

Jay Mody
Jay Mody

Reputation: 4033

It's not possible to remove the output message directly via nltk (as of August 2021). If you look at the code for nltk/book.py, you'll see the prints statements responsible for the message are written at the top level (global scope). When a module is first imported, all the code at the top level is executed (as if it were a script). So, the first time you import something from nltk.book, those print statements will execute.

While you can't prevent those print statements from executing, you could "catch" the output and prevent it from writing to stdout. I would highly advise against this, you don't want to end up in a situation where a warning/error message is printed to stdout as a result of the import, but it get's thrown away silently, and you end up scratching your head for hours trying to solve a weird bug that could've been prevented if you saw the error message. However, if you really want, here are some ways of doing so.

Upvotes: 4

Related Questions