NLTK是对英文文本数据进行处理的常用工具
- import nltk
- nltk.download('stopwords')
- from nltk.corpus import stopwords
- print(stopwords.words('english'))

2.1.1 找出古腾堡语料库中的emma原文
gutenberg下载地址:NLTK Corpora (网页内搜索gutenberg)
- import nltk
- from nltk.corpus import gutenberg
- nltk.download('gutenberg')
- print(gutenberg.raw("austen-emma.txt"))
2.2.1 sentence_polarity.categories():返回褒贬类别列表,即 ['neg','pos']
- from nltk.corpus import sentence_polarity
- [(sentence,category)
- for category in sentence_polarity.categories()
- for sentence in sentence_polarity.sents(categories = category)]
特色:定义了同义词集合,每个同义词集合由具有相同意义的词义组成。此外,WordNet还为每一个同义词集合提供了简短的释义,不同同义词集合之间还具有一定的语义关系。以下实验举dog为例:
WordNet下载地址:NLTK Corpora (网页内搜索owm-1.4)
3.1.1 返回dog的全部8个词义的synset
syns = wordnet.synsets("dog") # 返回dog的全部18个词义的synset
3.1.2 返回dog第一个词义的名称、定义以及样例
- firstName = syns[0].name()
- firstDefine = syns[0].definition()
- firstExample = syns[0].examples()

3.1.3 返回dog第一个词义的上位同义词集合
synsJh = syns[0].hypernyms()

3.1.4 返回dog与cat的同义词集合间的Wu-Palmer相似度
- dog = wordnet.synset('dog.n.01')
- cat = wordnet.synset('cat.n.01')
- Wp = dog.wup_similarity(cat)

为WordNet中每个同义词集合人工标注了三个情感值,依次是褒义、贬义和中性。
sentiwordnet下载地址:NLTK Corpora (网页内搜索sentiwordnet)
3.2.1 查看good在形容词(a)下的第一号语义
- from nltk.corpus import sentiwordnet
- print(sentiwordnet.senti_synset('good.a.01'))
分句punkt下载地址:NLTK Corpora (网页内搜索punkt)
4.1.1 引入text文本
text = gutenberg.raw("austen-emma.txt")
4.1.2 对text进行分句
sentences = sent_tokenize(text) # 对text进行分句
4.1.3 显示其中的一个句子
print(sentences[100]) # 显示其中的一个句子
主要是将单词和标点符号、空格等等拆分。
继4.1.3:
- from nltk import word_tokenize
- from nltk.tokenize import sent_tokenize
- from nltk.corpus import gutenberg
- text = gutenberg.raw("austen-emma.txt")
- sentences = sent_tokenize(text)
- print(word_tokenize(sentences[100]))

主要是根据词语所处的上下文,确定其具体的词性。
4.3.1 如何使用pos_tag对单个单词进行词性标记
- from nltk import pos_tag
- from nltk import word_tokenize
- print(pos_tag(word_tokenize("i am cxk , i like playing basketball")))
4.3.2 查询词性的标记意思
ragsets下载地址:NLTK Corpora (网页内搜索tagsets)
- import nltk.help
- print(nltk.help.upenn_tagset('NN'))