Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
680 views
in Technique[技术] by (71.8m points)

python - How to save nltk Text.similar() with variable

I'm a noob in nltk and python.Recently I got a problem,I want to save what text.similar() show in terminal in a variable,but I failed many times.How could I save it?

text = nltk.Text(word.lower() for word in nltk.corpus.brown.words())
save = []
for word in nltk.word_tokenize("i want to slove this problem"):
    save.append(text.similar(word))

Sadly,I found there is nothing in save[].Then I test code "word = text.similar('women')",I also found there is nothing in "word". I realized it seams I couldn't save text.similar(). What should I do to save it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instances of nltk.Text are really meant only for interactive exploration. It dumps a lot of stuff to the console, but really doesn't return any constructed objects from it's functions.

What you want in this case is the nltk.ContextIndex class. Using this class...

import nltk
import nltk.text
import nltk.corpus

idx = nltk.text.ContextIndex([word.lower( ) for word in nltk.corpus.brown.words( )])
save = [ ]
for word in nltk.word_tokenize("i want to solve this problem"):
    save.append(idx.similar_words(word))

When done, save will be a nest list of the most frequent words in the contexts of "i", "want", "to", etc.

Take a look at the online nltk.text.Text documentation, specifically the similar method, where it references nltk.text.ContextIndex


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...