简体   繁体   中英

Terminal printing results at another location?

Everyone. I am a beginner programmer, and I can't seem to find this information anywhere on the web, so I am hoping you guys can help. My problem is that sometimes when I try to print a result the terminal spits back something like "" or "", rather than the result. I am actually following very short, very simple lines of code straight out of a book and still getting these results.

Here are some examples to better show what is happening.

In the first example, "potato" is just the file handle name of a random text document.

import nltk
def diversity(potato):
    return len(potato) / len(set(potato))
print diversity(potato)
#prints <function diversity at 0x107b5a848>">

or

import nltk
print bigrams(['make', 'me', 'some', 'bigrams'])
#prints <generator object bigram at 0x1088a4d20> 

However in the examples in the text book just show the correct results printing. If it is at all important to know, I am specifically working with the book "Natural Language Processing with Python" by Bird, Klein, and Loper, and I am running Python 2.7.9.

Can anyone explain what is happening and how I can get around this? These are very simple lines of code with very simple answers, so the fact that my terminal seemingly refuses to print the correct answers is irritating and worrisome. Thank you!

The second example is very easy to explain.

The return value from the nltk.bigrams function is a generator . If you want to see the actual values that it returns you need to iterate over it and print its values:

In [11]: for bigram in  nltk.bigrams(['make', 'me', 'some', 'bigrams']):
   ....:     print bigram
   ....:     
('make', 'me')
('me', 'some')
('some', 'bigrams')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM