在 python 中使用 nltk.book 模块时删除初始文本

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

我正在学习 NLP 并使用 nltk,但只要在我的程序中导入模块,每当我 运行 脚本时,我都会得到以下文本:

*** 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

我知道这是关于模块的信息,但我现在不需要。有没有办法让控制台在我 运行 脚本时不打印它?

无法通过 nltk 直接删除输出消息(截至 2021 年 8 月)。如果您查看 nltk/book.py 的代码,您会看到负责消息的打印语句写在顶层(全局范围)。首次导入模块时,将执行顶层的所有代码(就像脚本一样)。因此,第一次从 nltk.book 导入内容时,将执行这些打印语句。

虽然您无法阻止这些打印语句的执行,但您可以“捕获”输出并阻止其写入标准输出。我强烈建议您不要这样做,您不希望由于导入而将 warning/error 消息打印到标准输出,但它会被悄无声息地丢弃,您最终会抓挠您的花几个小时试图解决一个奇怪的错误,如果您看到错误消息,这个错误本可以避免。但是,如果你真的想要,here are some ways of doing so.