[英]How to stop NLTK from outputting to terminal when downloading data?
When I run my program, which is using: 当我运行我正在使用的程序时:
nltk.download('wordnet')
from nltk.corpus import wordnet
I get the following output to my terminal: 我得到以下输出到我的终端:
[nltk_data] Downloading package wordnet to
[nltk_data] /Users/.../nltk_data...
[nltk_data] Package wordnet is already up-to-date!
My program relies on not having this information saved to the terminal and a resulting output file, so how can I prevent the above lines from occurring, or write it to sys.stderr
so it doesn't get included instead of it being through print
? 我的程序依赖于没有将这些信息保存到终端和生成的输出文件,那么如何防止上述行发生,或者将其写入
sys.stderr
以便它不会被包含而不是通过print
?
Use quiet=True
: 使用
quiet=True
:
import nltk
nltk.download('wordnet', quiet=True)
A much better solution is suggested in this answer . 在这个答案中提出了一个更好的解决方案。
Old Answer: 旧答案:
According to the source code , nltk
downloader uses straightforward print()
calls to report progress. 根据源代码 ,
nltk
下载程序使用简单的print()
调用来报告进度。 This means that there is no logger involved which you can control or pre-configure. 这意味着没有涉及可以控制或预配置的记录器。
One of the options is to modify the sys.stdout
temporarily on the fly - there is that redirect_stdout()
context manager in Python 3.4+: 其中一个选项是临时修改
sys.stdout
- Python 3.4+中有redirect_stdout()
上下文管理器 :
from contextlib import redirect_stdout
import os
import nltk
from nltk.corpus import wordnet
with redirect_stdout(open(os.devnull, "w")):
nltk.download('wordnet')
Or some other options: 或者其他一些选择:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.