user2120596
user2120596

Reputation: 35

Python: save the help result to a variable

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.

Upvotes: 2

Views: 327

Answers (2)

Manav Patadia
Manav Patadia

Reputation: 884

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']

Upvotes: 0

Riking
Riking

Reputation: 2481

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.

Upvotes: 1

Related Questions