2

Using python and NLTK I want to save the help result to a variable.

x = nltk.help.upenn_tagset('RB')

for example.

x variable is assigned with None. The console prints the result of the help function but it doesn't save that to var x.

mgilson
  • 300,191
  • 65
  • 633
  • 696
user2120596
  • 35
  • 1
  • 4
  • http://stackoverflow.com/questions/6796492/python-temporarily-redirect-stdout-stderr should help. You can redirect it to a StringIO object and then read from that. – mgilson Feb 28 '13 at 17:21
  • https://github.com/nltk/nltk/issues/205 – YXD Feb 28 '13 at 17:21

2 Answers2

1

Looking at the source file of help.py, it uses the print statement and doesn't return anything. upenn_tagset calls _format_tagset, which passes everything to _print_entries, which uses print.

So, what we really want to do is to redirect the print statement.

Quick search, and we've got https://stackoverflow.com/a/4110906/1210278 - replace sys.stdout.

As pointed out in the question linked by @mgilson, this is a permanent solution to a temporary problem. So what do we do? That should be easy - just keep the original around somewhere.

import sys
print "Hello"
cons_out = sys.stdout
sys.stdout = (other writable handle you can get result of)

do_printing_function()

sys.stdout = cons_out
print "World!"

This is actually exactly what the accepted answer at https://stackoverflow.com/a/6796752/1210278 does, except it uses a reusable class wrapper - this is a one-shot solution.

Community
  • 1
  • 1
Riking
  • 2,389
  • 1
  • 24
  • 36
0

Easiest way to get output of tag explanation is by loading whole tag-set and then extracting explanation of only required tags.

tags = nltk.data.load('help/tagsets/upenn_tagset.pickle')

tags['RB']
Manav Patadia
  • 848
  • 7
  • 12