Paolo
Paolo

Reputation: 2249

Save any output a function gives, into a variable

Being new at programming in general, and new with Python in particular, I'm having some beginner's troubles.

I'm trying out a function from NLTK called generate:

string.generate()

It returns what seems like a string. However, if I write:

stringvariable = string.generate()

or

stringvariable = str(string.generate())

… the stringvariable is always Empty.

So I guess I'm missing something here. Can the text output generated, that I see on the screen, be something else than a string output? And if so, is there any way for me to grab that output and put it into a variable?

Briefly put, how to I get what comes out of string.generate() into stringvariable, if not as described above?

Upvotes: 0

Views: 103

Answers (2)

Giuseppe Scrivano
Giuseppe Scrivano

Reputation: 1635

you can rewrite generate. The only disadvantage is that it can change and your code might not be updated to reflect these changes:

from nltk.util import tokenwrap
def generate_no_stdout(self, length=100):
    if '_trigram_model' not in self.__dict__:
        estimator = lambda fdist, bins: LidstoneProbDist(fdist, 0.2)
        self._trigram_model = NgramModel(3, self, estimator=estimator)
    text = self._trigram_model.generate(length)
    return tokenwrap(text)

then "a.generate()" becomes "generate_no_stdout(a)"

Upvotes: 1

Emre
Emre

Reputation: 6217

generate() prints its output rather than returning a string, so you need to capture it.

Upvotes: 0

Related Questions