我需要在python中使用NLTK库列出单词的所有形式(动词,名词,比较,最高级,形容词和副词)。例如,如果我有“#34;写"结果应该是:写作作家写的等......,如果这个词可以用比较和最高级的形式写成,例如;冷,然后更冷,最冷。快速:快速等等。有办法做到这一点吗?
答案 0 :(得分:3)
嗨,这是我迟到的答案。希望这仍然有帮助。我只是改进它一些小调试以适应新的nltk版本。原始代码可以在George-Bogdan Ivanov的答案中找到Convert words between verb/noun/adjective forms
from nltk.corpus import wordnet as wn
def morphify(word,org_pos,target_pos):
""" morph a word """
synsets = wn.synsets(word, pos=org_pos)
# Word not found
if not synsets:
return []
# Get all lemmas of the word
lemmas = [l for s in synsets \
for l in s.lemmas() if s.name().split('.')[1] == org_pos]
# Get related forms
derivationally_related_forms = [(l, l.derivationally_related_forms()) \
for l in lemmas]
# filter only the targeted pos
related_lemmas = [l for drf in derivationally_related_forms \
for l in drf[1] if l.synset().name().split('.')[1] == target_pos]
# Extract the words from the lemmas
words = [l.name() for l in related_lemmas]
len_words = len(words)
# Build the result in the form of a list containing tuples (word, probability)
result = [(w, float(words.count(w))/len_words) for w in set(words)]
result.sort(key=lambda w: -w[1])
# return all the possibilities sorted by probability
return result
print morphify('sadness','n','v')