当前位置: 首页 > news >正文

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

# using pip: 
pip install nltk
# using conda: 
conda install nltk

三、数据集的下载

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

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

import nltk
nltk.download()

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

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

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

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

from nltk.corpus import inaugural
inaugural.raw('1789-Washington.txt')

四、单词列表和词典

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

from nltk.corpus import words
words.fileids()

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

from nltk.corpus import stopwords 
stopwords.fileids()

五、语料库与词典

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

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

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

from nltk.corpus import opinion_lexicon
opinion_lexicon.negative()[:5]

六、NLTK 中的简单 NLP 任务:

# 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))
#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)
# Stemming
from nltk.stem import PorterStemmer
stemmer = PorterStemmer()
print(stemmer.stem("feet"))
# Lemmatization
import nltk
from nltk.stem.wordnet import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
print(lemmatizer.lemmatize("feet"))
# 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 任务,用于定位命名实体并将其分类为预定义的类别,例如人名、组织、位置、时间表达、数量、货币价值、百分比等。它有助于回答如下问题:

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

八、WordNet 语料库阅读器

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

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

import nltk
import string
#from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from nltk.corpus import movie_reviewsneg_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% recordsclf.show_most_informative_features()

九、结论

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

相关文章:

  • 解决Ubuntu系统NTFS速度过慢的问题
  • Docker(2)——Docker镜像的基本命令
  • Vscode LinuxC++环境配置
  • CentOS开机自动运行jar程序实现
  • Unity AssetBundle批量打包、加载(场景、Prefab)完整流程
  • MySQL数据库干货_16—— SQL99标准中的查询
  • Selenium元素定位之页面检测技巧
  • 【打卡】牛客网:BM35 判断是不是完全二叉树
  • vue的指令学习
  • 一座 “数智桥梁”,华为助力“天堑变通途”
  • golang工程——中间件redis,单节点集群部署
  • vue双向绑定失效,设置data值页面却不显示
  • 线性代数 第六章 二次型
  • 【代码数据】2023粤港澳大湾区金融数学建模B题分享
  • Centos部署清华ChatGLM3-6B详细教程
  • 345-反转字符串中的元音字母
  • angular学习第一篇-----环境搭建
  • Consul Config 使用Git做版本控制的实现
  • css属性的继承、初识值、计算值、当前值、应用值
  • Flannel解读
  • gcc介绍及安装
  • hadoop集群管理系统搭建规划说明
  • idea + plantuml 画流程图
  • JS字符串转数字方法总结
  • maya建模与骨骼动画快速实现人工鱼
  • MySQL数据库运维之数据恢复
  • niucms就是以城市为分割单位,在上面 小区/乡村/同城论坛+58+团购
  • Node 版本管理
  • node 版本过低
  • PhantomJS 安装
  • sessionStorage和localStorage
  • yii2中session跨域名的问题
  • 当SetTimeout遇到了字符串
  • 给Prometheus造假数据的方法
  • 基于组件的设计工作流与界面抽象
  • 那些被忽略的 JavaScript 数组方法细节
  • 容器化应用: 在阿里云搭建多节点 Openshift 集群
  • 写给高年级小学生看的《Bash 指南》
  • 译自由幺半群
  • #经典论文 异质山坡的物理模型 2 有效导水率
  • $.extend({},旧的,新的);合并对象,后面的覆盖前面的
  • (20)目标检测算法之YOLOv5计算预选框、详解anchor计算
  • (5)STL算法之复制
  • (done) ROC曲线 和 AUC值 分别是什么?
  • (LeetCode 49)Anagrams
  • (第61天)多租户架构(CDB/PDB)
  • (附源码)计算机毕业设计ssm基于Internet快递柜管理系统
  • (三) diretfbrc详解
  • (三)Pytorch快速搭建卷积神经网络模型实现手写数字识别(代码+详细注解)
  • (转)平衡树
  • (转)我也是一只IT小小鸟
  • . NET自动找可写目录
  • ./configure,make,make install的作用
  • ./和../以及/和~之间的区别
  • .NET CORE 2.0发布后没有 VIEWS视图页面文件