NLTK入门二:NLTK文本分析初步 顶

本文中的代码需要导入以下python包,其中For Jupyter notebook only之后的代码,对于非Jupyter notebook用户来说不需要导入。

import sys
import nltk
from IPython.display import display, clear_output
from nltk.book import *

# For Jupyter notebook only:
sys.path.append("/usr/lib/python3.6/site-packages/")
%matplotlib inline

文本导入:Python的read()方法以及word_tokenize(text)方法

下列程序以Modest Proposal 这本书为输入,将其中的每个单词放在text列表中。

import os

# import tokenizers
from nltk import word_tokenize
from nltk.text import Text

text_path = './The_Modest_Proposal.txt'

file = open(os.path.join(text_path), "r", encoding='UTF-8')
text = file.read()
print(text)

《NLTK入门二:NLTK文本分析初步 顶》

以下代码这可以将这本书的所有单词存入一个列表中供之后文本分析:

from nltk import word_tokenize
text = open('./The_Modest_Proposal.txt', "r", encoding='UTF-8').read() 
tokens = word_tokenize(text)
print(tokens[:100])

《NLTK入门二:NLTK文本分析初步 顶》

词性分析:pos_tag(word_list, [tagset])

NLTK提供文本词性分析的功能,如以下代码分析一句话中每个单词的词性:

sentence = "They refuse to permit us the refuse permit"
words = word_tokenize(sentence)
tagged = nltk.pos_tag(words, tagset='universal')
print(tagged)

《NLTK入门二:NLTK文本分析初步 顶》

然而由此可见,该词性分析功能对于一般的文本也不完全准确(如此处permit应该为一处动词一处名词)。以下统计文本中每种词性的词语出现的频率:

tagged_text = nltk.pos_tag(token_list, tagset = 'universal')
text_fd = nltk.FreqDist(tag for (word, tag) in tagged_text)
text_fd.most_common()

《NLTK入门二:NLTK文本分析初步 顶》

如果需要精确地知道词性,则需要把单词表转化为nltk.Text的对象,以下代码则能精确统计上述信息:

sentence = "They refuse to permit us the refuse permit"
words = nltk.Text(word_tokenize(sentence))
tagged = nltk.pos_tag(words, tagset='universal')
print(tagged)

《NLTK入门二:NLTK文本分析初步 顶》

以下程序统计普通文本中动词出现的情况:

verblist = []
for (word, tag) in tagged_text:
    if tag == 'VERB':
        verblist.append(word)
# Check the length of the list of verbs. 
#If it matches the number of verbs above, you can be fairly sure your loop has worked as expected
print(len(verblist))
verb_fd = nltk.FreqDist(verblist)
print(verb_fd.most_common()[:10])

《NLTK入门二:NLTK文本分析初步 顶》

类似地,可以统计名词(NOUN)、代词(PRON)甚至标点(.)的出现情况。

过滤“停用词”:nltk.corpus.stopwords.words(‘lang_type’):

停用词是指在文本中不含实际意义的单词,比如英文中的”is”, “the”, “at” 以及”which”等单词。它们在文本关键词的分析中往往不起实际作用。NLTK提供这些单词的列表,使之可以被过滤。以下代码能够过滤掉标点和功能词,并将文本中的单词全部转化为小写。

from nltk.corpus import stopwords

#First let's get rid of the puncutation
text = [word for word in nltk_text if word.isalpha()]
vocab = [word.lower() for word in text]

#Create a variable that contains all the stopwords in the NLTK corpus
ignored_words = stopwords.words('english')
unstopped = [word for word in vocab if word not in stopwords.words('english')]
fdist2 = nltk.FreqDist(unstopped)
fdist2.most_common()[:20]

《NLTK入门二:NLTK文本分析初步 顶》

以上代码也常用如下一行代码书写:

 unstopped = [word for word in speech if word.lower() not in stopwords.words('english') and word.isalpha()]

词组分析初步:nltk.collocations.BigramAssocMeasures(),BigramCollocationFinder.from_words(word_list), finder.nbest(bigram_measures.raw_freq, num) 以及ngram:

nltk有专门用于二元词组(两个单词组成的词组)统计的模块BigramAssocMeasures和BigramCollocationFinder。通过nbest可以输出出现频率靠前的二元词组。以下代码输出上文unstopped单词列表中最常出现的10个二元词组:

from nltk.collocations import *
bigram_measures = nltk.collocations.BigramAssocMeasures()
finder = BigramCollocationFinder.from_words(unstopped)
sorted(finder.nbest(bigram_measures.raw_freq, 10))

《NLTK入门二:NLTK文本分析初步 顶》

关于三个单词以上词组的词频分析,则要使用nltk.util.ngram模块:

from nltk.util import ngrams
trigrams = ngrams(unstopped, 3)
for gram in trigrams:
    print(gram)

《NLTK入门二:NLTK文本分析初步 顶》

国际化支持

本文中提到的一些方法也有用于其他语言的例子。然而由于语言之间有区别或者有些语言文本长度过于长(如尝试导入《天龙八部》),会导致程序运行出现一些问题。笔者也会关注这些问题,日后持续更新这方面信息。

参考资料:

  1. NLTK官方文档,http://www.nltk.org/
  2. NLTKbook模块官方文档,http://www.nltk.org/book/
  3. 墨尔本大学科研委员会(Resbaz)NLTK培训课程
  4. Jupyter notebook常见快捷键:https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcut
  5. 更改Jupyter notebook起始目录的四种方法,URL:https://blog.csdn.net/qq_33039859/article/details/54604533
    原文作者:python入门
    原文地址: https://my.oschina.net/Samyan/blog/1810872
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞