【火炉炼AI】机器学习036-NLP词形还原

1,489 阅读4分钟

【火炉炼AI】机器学习036-NLP词形还原

(本文所使用的Python库和版本号: Python 3.6, Numpy 1.14, scikit-learn 0.19, matplotlib 2.2, NLTK 3.3)

词形还原也是将单词转换为原来的相貌,和上一篇文章中介绍的词干提取不一样,词形还原要难的多,它是一个更加结构化的方法,在上一篇中的词干提取例子中,可以看到将wolves提取为wolv等,这些肯定不是我们所期望的。那么此处我们使用NLP词形还原的方式来将英语单词还原。


1. NLP词形还原

词形还原是基于字典的映射,而且,NLTK还要求手动注明词形,否则可能会还原不准确,所以在做自然语言处理的过程中,先对文本进行分词,然后标注词性,最后再进行词形还原。

# 待还原的单词
words = ['table', 'probably', 'wolves', 'playing', 'is', 
        'dog', 'the', 'beaches', 'grounded', 'dreamt', 'envision']

# 由于词形还原需要先标注词性,故而此处我们用名词和动词两种词性进行测试
lemmatizers = ['NOUN LEMMATIZER', 'VERB LEMMATIZER'] # 两种词性
lemmatizer = WordNetLemmatizer()
formatted_row = '{:>24}' * (len(lemmatizers) + 1) # 使其打印格式一致
print(formatted_row.format('WORD',*lemmatizers)) # 打印表头

for word in words: # # 每个单词逐一变换
    lemmatized=[lemmatizer.lemmatize(word, pos='n'), lemmatizer.lemmatize(word, pos='v')]
    # 注意里面pos表示词性,分别表示名称和动词
    print(formatted_row.format(word,*lemmatized)) # 对提取后的stem进行拆包

---------------------------输---------出--------------------------------

                WORD         NOUN LEMMATIZER         VERB LEMMATIZER
               table                   table                   table
            probably                probably                probably
              wolves                    wolf                  wolves
             playing                 playing                    play
                  is                      is                      be
                 dog                     dog                     dog
                 the                     the                     the
             beaches                   beach                   beach
            grounded                grounded                  ground
              dreamt                  dreamt                   dream
            envision                envision                envision

------------------------------完-------------------------------------

可以看出,虽然WordNetLemmatizer很有用,但是需要事先判断词性,并且把词性作为一个参数传入到这个函数中,那么有没有可能自动判断词性,不需要我们认为判断了?这是肯定的,NLTK有一个函数pos_tag可以自动判断出某个单词的词性,所以基于此,我们可以编写一个函数,来自动处理一整个句子,输出器词性还原之后的形式。如下代码:

# 定义一个函数来对一个句子中的所有单词进行词形还原
def lemmatize_all(sentence):
    wnl = WordNetLemmatizer()
    for word, tag in pos_tag(word_tokenize(sentence)):
        if tag.startswith('NN'):
            yield wnl.lemmatize(word, pos='n')
        elif tag.startswith('VB'):
            yield wnl.lemmatize(word, pos='v')
        elif tag.startswith('JJ'):
            yield wnl.lemmatize(word, pos='a')
        elif tag.startswith('R'):
            yield wnl.lemmatize(word, pos='r')
        else:
            yield word

text ='dog runs, cats drunk wines, chicken eat apples, foxes jumped two meters'
print('/'.join(lemmatize_all(text)))

---------------------------输---------出--------------------------------

dog/run/,/cat/drink/wine/,/chicken/eat/apple/,/fox/jump/two/meter

---------------------------------完-------------------------------------

可以看出,句子中的名词复数都转变为了单数,动词过去式都转变为了现在式等。

关于pos_tag()函数,返回的是单词和词性标签,这些词性标签有:

# NLTK 词性标签: 
CC 连词 and, or,but, if, while,although
CD 数词 twenty-four, fourth, 1991,14:24
DT 限定词 the, a, some, most,every, no
EX 存在量词 there, there's
FW 外来词 dolce, ersatz, esprit, quo,maitre
IN 介词连词 on, of,at, with,by,into, under
JJ 形容词 new,good, high, special, big, local
JJR 比较级词语 bleaker braver breezier briefer brighter brisker
JJS 最高级词语 calmest cheapest choicest classiest cleanest clearest
LS 标记 A A. B B. C C. D E F First G H I J K
MD 情态动词 can cannot could couldn't
NN 名词 year,home, costs, time, education
NNS 名词复数 undergraduates scotches
NNP 专有名词 Alison,Africa,April,Washington
NNPS 专有名词复数 Americans Americas Amharas Amityvilles
PDT 前限定词 all both half many
POS 所有格标记 ' 's
PRP 人称代词 hers herself him himself hisself
PRP$ 所有格 her his mine my our ours
RB 副词 occasionally unabatingly maddeningly
RBR 副词比较级 further gloomier grander
RBS 副词最高级 best biggest bluntest earliest
RP 虚词 aboard about across along apart
SYM 符号 % & ' '' ''. ) )
TO 词to to
UH 感叹词 Goodbye Goody Gosh Wow
VB 动词 ask assemble assess
VBD 动词过去式 dipped pleaded swiped
VBG 动词现在分词 telegraphing stirring focusing
VBN 动词过去分词 multihulled dilapidated aerosolized
VBP 动词现在式非第三人称时态 predominate wrap resort sue
VBZ 动词现在式第三人称时态 bases reconstructs marks
WDT Wh限定词 who,which,when,what,where,how
WP WH代词 that what whatever
WP$ WH代词所有格 whose
WRB WH副词

########################小**********结###############################

1,NLP词形还原可以使用WordNetLemmatizer函数,但是这个函数在使用前需要先判断某个单词的词性,然后将词性作为参数输入到这个函数中进行转换。

2,为了简化这种人为判断的过程,NLTK有自带的词性判断函数pos_tag,这个函数可以自动输出某个单词的词性,所以将pos_tag和WordNetLemmatizer函数联合起来,可以自动对某一整段文本进行分词,词形还原等操作。

#################################################################


注:本部分代码已经全部上传到(我的github)上,欢迎下载。

参考资料:

1, Python机器学习经典实例,Prateek Joshi著,陶俊杰,陈小莉译