如何在单词表中只保留名词单词?python NLTK



我有一个词表,它包含许多主题。从句子中自动提取主语。我想把名词和主语分开。正如你所看到的,一些主题有形容词,我想删除它。

wordlist=['country','all','middle','various drinks','few people','its reputation','German Embassy','many elections']
returnlist=[]
for word in wordlist:
    x=wn.synsets(word)
    for syn in x:
        if syn.pos() == 'n':
            returnlist.append(word)
            break
print returnlist

以上结果为:

['country','it',  'middle']

然而,我想得到的结果应该是这样的

   wordlist=['country','it', 'middle','drinks','people','reputation','German Embassy','elections']

怎么做?

首先,你的列表是没有很好地标记文本的结果,所以我再次标记它们然后搜索所有单词的pos,找到包含NN的名词:

>>> text=' '.join(wordlist).lower()
>>> tokens = nltk.word_tokenize(text)
>>> tags = nltk.pos_tag(tokens)
>>> nouns = [word for word,pos in tags if (pos == 'NN' or pos == 'NNP' or pos == 'NNS' or pos == 'NNPS')
]
>>> nouns
['country', 'drinks', 'people', 'Embassy', 'elections']
adjectives = ['many', 'any', 'few', 'some', 'various'] # ...
wordlist = ['country','all','middle','various drinks','few people','its reputation','German Embassy','many elections']
returnlist = []
for word in wordlist:
    for adj in adjectives:
        word = word.lower().replace(adj, '').strip()
    returnlist.append(word)
print(returnlist)

最新更新