我是nltk和python的菜鸟。最近我遇到了一个问题,我想将终端中显示的text.similar()保存在一个变量中,但是我失败了很多次。我该如何保存呢?
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))
遗憾的是,我发现save[]里什么也没有。然后我测试代码“word = text.similar('women')”,我也发现“word”里什么也没有。我意识到它接缝我无法保存 text.similar()。 我应该怎么做才能挽救它?
请您参考如下方法:
nltk.Text 的实例实际上仅用于交互式探索。它向控制台转储了很多东西,但实际上并没有从它的函数中返回任何构造的对象。
在这种情况下,您需要的是 nltk.ContextIndex 类。使用这个类...
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))
完成后,save 将是“i”、“want”、“to”等上下文中最常用词的嵌套列表。
看看 online nltk.text.Text documentation ,特别是 similar 方法,它引用了 nltk.text.ContextIndex
