NLTK“生成”功能:如何取回返回的文本?
我是一个 Python 菜鸟,所以请耐心等待。
我正在尝试使用 NLTK 库,特别是“生成”函数。从文档来看,该函数只是打印其结果( http://nltk.googlecode.com/svn/trunk/doc/api/nltk.text-pysrc.html)。我想在将结果文本打印到屏幕上之前对其进行操作,但我似乎无法弄清楚如何让此函数返回其文本。
我将如何获取该函数的输出?我是否必须更改函数以返回结果而不是打印结果?
更新:我发现这个链接有点像它,但感觉非常糟糕。 http://northernplanets.blogspot.com/2006 /07/capturing-output-of-print-in-python.html 这是我能期望的最好结果吗?
I'm a Python noob, so bear with me.
I'm trying to work with the NLTK library, and in particular the 'generate' function. It looks like from the documentation this function simply prints its result (http://nltk.googlecode.com/svn/trunk/doc/api/nltk.text-pysrc.html). I would like to manipulate the resulting text prior to printing it to the screen, but I can't seem to figure out how to get this function to return its text.
How would I go about getting the output of this function? Do I have to change the function to return the result instead of printing it?
UPDATE: I found this link which kinda does it, but it feels pretty darn hacky. http://northernplanets.blogspot.com/2006/07/capturing-output-of-print-in-python.html Is this the best I can hope for?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
generate
所做的就是生成一个三元模型(如果不存在),然后调用、包装并打印它。
只需获取您想要的部分 - 可能只是上面的行(将print替换为
self
替换为实例名称),或者可能是整个内容,如下所示,以及最终的return
。然后您可以使用手动传递的实例作为第一个参数来调用它。
All
generate
is doing is generating a trigram model if none exists, then callingand wrapping and printing it.
Just take the parts you want -- possibly just the above line (with
self
replaced by the instance name), or possibly the whole thing, as below, with the finalprint
replaced withreturn
.And then you can just call it with a manually passed instance as the first argument.
进入 Python26/site-packages/nltk/text.py 并更改“生成”函数:
Go into Python26/site-packages/nltk/text.py and change the "generate" function: