NLP学习笔记:使用 Python 进行NLTK

一、说明

本文和接下来的几篇文章将介绍 Python NLTK 库。NLTK --- 自然语言工具包 --- NLTK 是一个强大的开源库,用于 NLP 的研究和开发。它内置了 50 多个文本语料库和词汇资源。它支持文本标记化、词性标记、词干提取、词形还原、命名实体提取、分割、分类、语义推理。

Python 有一些非常强大的 NLP 库。SpaCY --- SpaCy 也是一个开源 Python 库,用于构建现实世界项目的生产级别。它内置了对 BERT 等多重训练 Transformer 的支持,以及针对超过 17 种语言的预训练 NLP 管道。它速度非常快,并提供以下功能 - 超过 49 种语言的标记化、词性标记、分段、词形还原、命名实体识别、文本分类。

TextBlob --- TextBlob 是一个构建在 NLTK 之上的开源库。它提供了一个简单的界面,并支持诸如情感分析、短语提取、解析、词性标记、N-gram、拼写纠正、标记分类、名词短语提取等任务。

Gensim --- GenSim 支持分层狄利克雷过程 (HDP)、随机投影、潜在狄利克雷分配 (LDA)、潜在语义分析或 word2vec 深度学习等算法。它非常快并且优化了内存使用。

PolyGlot --- PolyGlot 支持多种语言,并基于 SpaCy 和 NumPy 库构建。它支持165种语言的标记化、196种语言的语言检测、命名实体识别、POS标记、情感分析、137种语言的词嵌入、形态分析、69种语言的音译。

sklearn --- Python 中的标准机器学习库

自然语言工具包(NLTK)

NLTK 是一个免费的开源 Python 库,用于在 Windows、Mac OS X 和 Linux 中构建 NLP 程序。它拥有 50 个内置语料库、WordNet 等词汇资源以及许多用于 NLP 任务(如分类、分词、词干、标记、解析、语义推理)的库。

NLTK 提供了编程基础知识、计算语言学概念和优秀文档的实践指南,这使得 NLTK 非常适合语言学家、工程师、学生、教育工作者、研究人员和行业用户等使用。NLTK 有一本姊妹书------由 NLTK 的创建者编写的《Python 自然语言处理》。

二、下载并安装NLTK

ba 复制代码
# using pip: 
pip install nltk
# using conda: 
conda install nltk

三、数据集的下载

数据集下载的地址是:NLTK Data

NLTK附带了许多语料库、玩具语法、训练模型等。安装NLTK后,我们应该使用NLTK的数据下载器安装数据:

ba 复制代码
import nltk
nltk.download()

应打开一个新窗口,显示 NLTK 下载程序。您可以选择要下载的语料库。您也可以下载全部。

NLTK 包括一组不同的语料库,可以使用 nltk.corpus 包读取。每个语料库都通过 nltk.corpus 中的"语料库阅读器"对象进行访问:

ba 复制代码
# Builtin corpora in NLTK (https://www.nltk.org/howto/corpus.html)
import nltk.corpus
from nltk.corpus import brown
brown.fileids()

每个语料库阅读器都提供多种从语料库读取数据的方法,具体取决于语料库的格式。例如,纯文本语料库支持将语料库读取为原始文本、单词列表、句子列表或段落列表的方法。

ba 复制代码
from nltk.corpus import inaugural
inaugural.raw('1789-Washington.txt')

四、单词列表和词典

NLTK 数据包还包括许多词典和单词列表。这些的访问就像文本语料库一样。以下示例说明了词表语料库的使用:

ba 复制代码
from nltk.corpus import words
words.fileids()

停用词:对文本含义添加很少或没有添加的单词。

ba 复制代码
from nltk.corpus import stopwords 
stopwords.fileids()

五、语料库与词典

语料库是特定语言的文本数据(书面或口头)的大量集合。语料库可能包含有关单词的附加信息,例如它们的 POS 标签或句子的解析树等。

词典是语言的词位(词汇)的整个集合。许多词典包含一个核心标记(lexeme)、其名词形式、形容词形式、相关动词、相关副词等、其同义词、反义词等。

NLTK提供了一个opinion_lexicon,其中包含英语正面和负面意见词的列表

ba 复制代码
from nltk.corpus import opinion_lexicon
opinion_lexicon.negative()[:5]

六、NLTK 中的简单 NLP 任务:

ba 复制代码
# Tokenization
from nltk import word_tokenize, sent_tokenize
sent = "I will walk 500 miles and I would walk 500 more, just to be the man who walks a thousand miles to fall down at your door!"
print(word_tokenize(sent))
print(sent_tokenize(sent))
ba 复制代码
#Stopwords removal
from nltk.corpus import stopwords        # the corpus module is an extremely useful one. 
sent = "I will pick you up at 5.00 pm. We will go for a walk"                                         
stop_words = stopwords.words('english')  # this is the full list of all stop-words stored in nltk
token = nltk.word_tokenize(sent)
cleaned_token = []
for word in token:
    if word not in stop_words:
        cleaned_token.append(word)
print("This is the unclean version:", token)
print("This is the cleaned version:", cleaned_token)
ba 复制代码
# Stemming
from nltk.stem import PorterStemmer
stemmer = PorterStemmer()
print(stemmer.stem("feet"))
ba 复制代码
# Lemmatization
import nltk
from nltk.stem.wordnet import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
print(lemmatizer.lemmatize("feet"))
ba 复制代码
# POS tagging
from nltk import pos_tag 
from nltk.corpus import stopwords 

stop_words = stopwords.words('english')

sentence = "The pos_tag() method takes in a list of tokenized words, and tags each of them with a corresponding Parts of Speech"
tokens = nltk.word_tokenize(sentence)

cleaned_token = []
for word in tokens:
    if word not in stop_words:
        cleaned_token.append(word)
tagged = pos_tag(cleaned_token)                 
print(tagged)

七、命名实体识别:

NER 是 NLP 任务,用于定位命名实体并将其分类为预定义的类别,例如人名、组织、位置、时间表达、数量、货币价值、百分比等。它有助于回答如下问题:

  • 报告中提到了哪些公司?
  • 该推文是否谈到了特定的人?
  • 新闻文章中提到了哪些地方、哪些公司?
  • 正在谈论哪种产品?
ba 复制代码
entities = nltk.chunk.ne_chunk(tagged)
entities

八、WordNet 语料库阅读器

WordNet 是 WordNet 的 NLTK 接口。WordNet 是英语词汇数据库。WordNet 使用 Synsets 来存储单词。同义词集是一组具有共同含义的同义词。使用同义词集,它有助于找到单词之间的概念关系。

使用 NLTK 朴素贝叶斯分类器构建电影评论分类器

ba 复制代码
import nltk
import string
#from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from nltk.corpus import movie_reviews

neg_files = movie_reviews.fileids('neg')
pos_files = movie_reviews.fileids('pos')


def feature_extraction(words):
    stopwordsandpunct = nltk.corpus.stopwords.words("english") + list(string.punctuation)
    return { word:'present' for word in words if not word in stopwordsandpunct}

neg_words = [(feature_extraction(movie_reviews.words(fileids=[f])), 'neg') for f in neg_files]
pos_words = [(feature_extraction(movie_reviews.words(fileids=[f])), 'pos') for f in pos_files]

from nltk.classify import NaiveBayesClassifier #load the buildin classifier
clf = NaiveBayesClassifier.train(pos_words[:500]+neg_words[:500])  
#train it on 50% of records in positive and negative reviews
nltk.classify.util.accuracy(clf, pos_words[500:]+neg_words[500:])*100  #test it on remaining 50% records


clf.show_most_informative_features()

九、结论

本文记载了NLTK库的部分使用常识,其中重要点是:1)数据集从哪里去找。2)如何使用这个库 3)如何读取语料集。 这些对通常实验或项目开发有很重要的参考价值。

相关推荐
金井PRATHAMA5 小时前
描述逻辑对人工智能自然语言处理中深层语义分析的影响与启示
人工智能·自然语言处理·知识图谱
纵横八荒5 小时前
Java基础加强13-集合框架、Stream流
java·开发语言
codists6 小时前
2025年9月文章一览
python
语落心生6 小时前
FastDeploy SD & Flux 扩散模型边缘端轻量化推理部署实现
python
欣然~6 小时前
百度地图收藏地址提取与格式转换工具 说明文档
java·开发语言·dubbo
java1234_小锋6 小时前
TensorFlow2 Python深度学习 - TensorFlow2框架入门 - 立即执行模式(Eager Execution)
python·深度学习·tensorflow·tensorflow2
William_cl6 小时前
C# MVC 修复DataTable时间排序以及中英文系统的时间筛选问题
开发语言·c#·mvc
running thunderbolt6 小时前
项目---网络通信组件JsonRpc
linux·服务器·c语言·开发语言·网络·c++·性能优化
王大傻09286 小时前
numpy -- 算术函数 reciprocal() 和 power() 简介
python·numpy
小马学嵌入式~6 小时前
堆排序原理与实现详解
开发语言·数据结构·学习·算法