简体   繁体   English

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

[英]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:我正在学习 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

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?有没有办法让它在我运行脚本时控制台不打印它?

It's not possible to remove the output message directly via nltk (as of August 2021).无法通过nltk直接删除 output 消息(截至 2021 年 8 月)。 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).如果您查看nltk/book.py的代码,您会看到负责消息的打印语句写在顶层(全局范围)。 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.因此,第一次从nltk.book导入内容时,这些打印语句将执行。

While you can't prevent those print statements from executing, you could "catch" the output and prevent it from writing to stdout.虽然您无法阻止这些打印语句的执行,但您可以“捕获”output 并阻止它写入标准输出。 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 .但是,如果您真的想要, 这里有一些方法可以做到

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM