nltk.文本:未获得所需结果

2024-10-16 20:48:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着从一些文本中提取关键字

t="""Two Travellers, walking in the noonday sun, sought the shade of a widespreading tree to rest. As they lay looking up among the pleasant leaves, they saw that it was a Plane Tree.

"How useless is the Plane!" said one of them. "It bears no fruit whatever, and only serves to litter the ground with leaves."

"Ungrateful creatures!" said a voice from the Plane Tree. "You lie here in my cooling shade, and yet you say I am useless! Thus ungratefully, O Jupiter, do men receive their blessings!"

Our best blessings are often the least appreciated."""

    text = nltk.Text(word.lower() for word in t.split(" "))
    print text.similar('tree')

但我明白了

None

为什么?你知道吗

编辑

按照安迪的建议,我试过了

import nltk
import nltk.text
import nltk.corpus
t="""Two Travellers, walking in the noonday sun, sought the shade of a widespreading tree to rest As they lay looking up among the pleasant leaves, they saw that it was a Plane Tree 
How useless is the Plane!" said one of them. "It bears no fruit whatever, and only serves to litter the ground with leaves."

"Ungrateful creatures!" said a voice from the Plane Tree. "You lie here in my cooling shade, and yet you say I am useless! Thus ungratefully, O Jupiter, do men receive their blessings!"

Our best blessings are often the least appreciated"""
idx = nltk.text.ContextIndex([word.lower( ) for word in t.split(" ")])
print idx.tokens()
idx.similar_words('tree')
for word in nltk.word_tokenize("tree"):
    print idx.similar_words(word)

但这让我

['two', 'travellers,', 'walking', 'in', 'the', 'noonday', 'sun,', 'sought', 'the', 'shade', 'of', 'a', 'widespreading', 'tree', 'to', 'rest', 'as', 'they', 'lay', 'looking', 'up', 'among', 'the', 'pleasant', 'leaves,', 'they', 'saw', 'that', 'it', 'was', 'a', 'plane', 'tree', '\nhow', 'useless', 'is', 'the', 'plane!"', 'said', 'one', 'of', 'them.', '"it', 'bears', 'no', 'fruit', 'whatever,', 'and', 'only', 'serves', 'to', 'litter', 'the', 'ground', 'with', 'leaves."\n\n"ungrateful', 'creatures!"', 'said', 'a', 'voice', 'from', 'the', 'plane', 'tree.', '"you', 'lie', 'here', 'in', 'my', 'cooling', 'shade,', 'and', 'yet', 'you', 'say', 'i', 'am', 'useless!', 'thus', 'ungratefully,', 'o', 'jupiter,', 'do', 'men', 'receive', 'their', 'blessings!"\n\nour', 'best', 'blessings', 'are', 'often', 'the', 'least', 'appreciated']
[]

所以单词tree在tokens列表中是int。为什么我没有得到类似函数的任何输出?你知道吗


Tags: andofthetointreewordleaves