如何在python中使用NLTK列出单词的所有形式

ANj*_*ell 5 nltk python-2.7

我需要使用python中的NLTK库列出单词的所有形式(动词,名词,比较词,最高级词,形容词和副词)。例如,如果我有“ write”一词,则结果应为:writing writer writer writer等...,如果该词可以比较和最高级形式书写,例如;冷然后更冷,最冷。快速:快速等。有没有办法做到这一点?

小智 3

嗨,这是我迟来的答案。希望这仍然有帮助。我只是对其进行了一些改进和一些小的调试以适应新的 nltk 版本。原始代码可以在 George-Bogdan Ivanov 的答案中找到,在动词/名词/形容词形式之间转换单词

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')
Run Code Online (Sandbox Code Playgroud)