自然语言处理(Natural Language Processing,NLP)是人工智能领域中非常重要的一个研究方向,其用于在计算机上自动执行的自然语言操作包括文本分类、文本摘要、文本翻译、情感分析、机器翻译等。下面将介绍常用的自然语言处理库及其示例代码。
Natural Language Processing
NLTK
NLTK(Natural Language Toolkit,自然语言工具包)是一个用于英语自然语言处理和文本分析的Python库。NLTK由美国宾夕法尼亚大学(University of Pennsylvania)计算机和信息科学系的Steven Bird和Edward Loper开发,旨在支持自然语言处理及相关领域的研究和教学,包括语言学、认知科学、人工智能、信息检索、机器学习,由于NLTK的实用性和覆盖广度,它在工业研究和开发中得到了广泛应用。
NLTK - A leading platform for building Python programs to work with human language data.
import nltk
text = "Today is a beautiful day. Tomorrow looks like bad weather."
# 分句
sentences = nltk.sent_tokenize(text)
for sent_no, sentence in enumerate(sentences):
# 分词
tokens = nltk.word_tokenize(sentence)
# 词性标注
tags = nltk.pos_tag(tokens)
# 获取所有名词
nouns = [word for word, pos in tags if pos in ['NN','NNP'] ]
print((sent_no, sentence, tags, nouns))
Pattern
Pattern是一个用于数据挖掘的Python库,同时实现了自然语言处理、机器学习、网络爬虫和可视化等功能。
Pattern - A web mining module for the Python programming language. It has tools for natural language processing, machine learning, among others.
from pattern.en import tag
from pattern.en import parse
from pattern.en import pprint
text = "I eat pizza with a fork."
# 文本解析
parsed = parse(text, tokenize=True, tags=True, chunks=True, relations=False, lemmata=False)
pprint(parsed)
# 词性标注
tags = tag(text)
# 获取所有名词
nouns = [word for word, pos in tags if pos in ['NN','NNP'] ]
print(tags)
print(nouns)
TextBlob
TextBlob是一个用于处理文本数据的Python库。TextBlob是基于NLTK和Pattern的英文文本处理工具包,用于深入研究常见的自然语言处理任务,例如词性标注、名词短语提取、情感分析、分类、翻译等。
TextBlob - Providing a consistent API for diving into common natural language processing (NLP) tasks. Stands on the giant shoulders of NLTK and Pattern, and plays nicely with both.
import textblob
text = "Today is a beautiful day. Tomorrow looks like bad weather."
blob = textblob.TextBlob(text)
# 分句:Sentence对象列表
print(blob.sentences)
# 分词:WordList对象
print(blob.words)
# 词性元组列表,每个元组包含单词和表示其词性的字符串
print(blob.tags)
# 名词短语提取:WordList对象
print(blob.noun_phrases)
SpaCy
SpaCy是一个用Python和Cython开发的工业级强度的自然语言处理软件库。SpaCy比NLTK新,速度更快,精度更高,更适合工业场景。
spacy - A library for industrial-strength natural language processing in Python and Cython.
import spacy
text = "I eat pizza with a fork."
# 加载语言模型
nlp = spacy.load("en_core_web_sm")
# 文本解析
doc = nlp(text)
for token in doc:
# 分词,词性标注,停用词
print(token.text, "\t", token.pos_, "\t", token.is_stop)
说明:由于某些原因下载失败时,可以从spacy-models下载模型手动安装
步骤一:查看spacy版本
pip show spacy
步骤二:下载支持对应spacy版本的模型:sm(small模型)、md(middle模型)、lg(large模型)、trf(transformer模型)
https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.7.1/en_core_web_sm-3.7.1-py3-none-any.whl
步骤三:安装本地模型
pip install C:\Users\lei.tian\Downloads\en_core_web_sm-3.7.1-py3-none-any.whl
Gensim
Gensim(Generate Similar)是一个用于主题模型(topic modelling)、文档索引(document indexing)和大型语料库的相似度检索(similarity retrieval with large corpora)的Python库。
gensim - Topic Modelling for Humans.
主题模型在机器学习和自然语言处理等领域是用来在一系列文档中发现抽象主题的一种统计模型。主题模型自动分析每个文档,统计文档内的词语,根据统计的信息来断定当前文档含有哪些主题,以及每个主题所占的比例各为多少。
- 隐式语义索引(Latent Semantic Indexing,LSI):潜在语义分析(LatentSemantic Analysis,LSA)
- 概率性隐式语义索引(Probabilistic Latent Semantic Indexing,PLSI)
- 隐式狄利克雷分布(Latent Dirichlet Allocation,LDA)
Stanza
Stanza是一个用于自然语言处理的Python库(v1.0.0之前称为StanfordNLP),基于神经网络、支持多种语言。
Stanza - The Stanford NLP Group's official Python library, supporting 60+ languages.
import stanza
text = "I eat pizza with a fork."
# 加载语言模型:stanza用法与spacy类似
nlp = stanza.Pipeline('en', verbose=False)
# 文本解析
doc = nlp(text)
for sentence in doc.sentences:
for word in sentence.words:
# 分词,词性标注
print(word.text, word.pos)
说明:由于某些原因下载失败时,可以下载模型并手动安装,详见stanfordnlp.github.io/stanza/down…
步骤一:下载resources_1.8.0.json到C:\Users\lei.tian\stanza_resources目录下,并重命名为resources.json---如果resources.json存在,则不需要
https://github.com/stanfordnlp/stanza-resources/blob/main/resources_1.8.0.json
步骤二:下载英语语言模型(default.zip)到C:\Users\lei.tian\stanza_resources\en目录下
https://huggingface.co/stanfordnlp/stanza-en/resolve/main/models/default.zip?download=true
步骤三:将default.zip解压缩当前目录
Polyglot
Polyglot(通晓多种语言的;多语者)是一个用于多语言处理的Python库,可以实现多语种的多个NLP任务处理。
Polyglot - Multilingual text (NLP) processing toolkit.
import polyglot
from polyglot.detect import Detector
from polyglot.text import Text
# 语言检测
print(Text("This is a test").language)
print(Detector("这是一个测试").language)
# for language in Detector("这是一个测试").languages:
# print(language)
# 标记化
text = Text("Mark is studying at Stanford University in California.")
print(text.words)
print(text.sentences)
print(text.sentences[0].words)
# 词性标注
print(text.pos_tags)
# 命名实体识别
print(text.entities)
Jieba
Jieba是一个用于处理中文分词的Python库,可以将中文文本切分成单个词语。将句子分开朗读听起来就像结巴说话一样!
jieba - The most popular Chinese text segmentation library.
import jieba
import jieba.posseg
import jieba.analyse
text = "我爱北京天安门"
# 分词:默认精确模式
words = jieba.lcut(text)
print(words)
# 返回分词结果中词语在原文的起止位置
result = jieba.tokenize(text)
for tk in result:
print("start:%d\tend:%d\tword:%s" % (tk[1], tk[2], tk[0]))
# 词性标注
words = jieba.posseg.lcut(text)
for word, flag in words:
print('%s\t%s' % (word, flag))
# 关键词提取
keywords = jieba.analyse.extract_tags(text, topK=3, withWeight=True)
print(keywords)
PKUSeg
PKUSeg(Peking University segmentation)是一个多领域中文分词工具包,由北京大学语言计算与机器学习研究组开发,具有较高的分词准确率。不同于以往的通用中文分词工具,此工具包同时致力于为不同领域的数据提供个性化的预训练模型,目前细分领域(专业领域)支持了新闻领域,网络领域,医药领域,旅游领域,以及混合领域的分词预训练模型。预训练模型(pre-trained model)和自训练模型(user-trained model)
pkuseg-python - A toolkit for Chinese word segmentation in various domains.
import pkuseg
# 无法明确分词领域,使用混合领域模型进行分词和词性标注
seg = pkuseg.pkuseg(postag=True)
text = seg.cut('我爱北京天安门')
print(text)
# 明确分词领域,使用细分领域模型进行分词和词性标注
seg = pkuseg.pkuseg(model_name='medicine', postag=True)
text = seg.cut('我爱北京天安门')
print(text)
说明:使用细领域模型或词性标注时程序会自动下载相关模型。由于某些原因下载失败时,可以到GitHub的Release页面手动下载,将模型文件(medicine.zip)解压缩到~/.pkuseg。
SnowNLP
SnowNLP是一个用于处理中文文本内容的Python库,SnowNLP是受到TextBlob的启发而写的,但没有使用NLTK,所有的算法都是自己实现的,并且自带了一些训练好的字典。
SnowNLP - A library for processing Chinese text.
import snownlp
text = "我爱北京天安门"
s = snownlp.SnowNLP(text)
# 中文分词
print(s.words, s.sentences)
# 词性标注
print(list(s.tags))
# 情感分析
print(s.sentiments)
# 词频-逆向文件频率
print(s.tf, s.idf)
# 文本关键字
print(s.keywords(limit=3))
# 文本摘要
print(s.summary(limit=3))
# 拼音转换
print(snownlp.SnowNLP("自然语言处理").pinyin)
# 繁简转换
print(snownlp.SnowNLP("「繁體字」「繁體中文」的叫法在臺灣亦很常見").han)
HanLP
HanLP(Han Language Processing,汉语言处理)是一个面向生产环境的多语种自然语言处理工具包,它基于PyTorch和TensorFlow 2.x双引擎。HanLP提供RESTful(云端)和Native(本地)两种API,分别面向轻量级和海量级两种场景。
HanLP有1.x和2.x两大版本
- 追求最强大、精准、先进的前沿技术,选择2.x。面向次世代进化,2.x分支革新大规模先端模型与语料库,支持多语种多任务,持续高速迭代研发。pip install hanlp
- 追求最经典、稳定、高效的生产系统,选择1.x。作为最后的武士,1.x分支将继续提供稳定性维护,但不会增加新功能。pip install pyhanlp
import hanlp
import hanlp_restful
text = "我爱北京天安门"
#######################RESTful API#######################
# class hanlp_restful.HanLPClient(url: str, auth: Optional[str] = None, language=None, timeout=60, verify=True)
# 创建客户端:auth不填则匿名,zh中文,mul多语种---由于服务器算力有限,匿名用户每分钟限2次调用
HanLP = hanlp_restful.HanLPClient('https://www.hanlp.com/api', auth=None, language='zh')
# 粗分标准(MSR,Microsoft Research)中文分词:适合文本挖掘业务
print(HanLP.tokenize(text, coarse=True))
# 细分标准(CTB,Penn Chinese Treebank)中文分词:适合搜索引擎业务
print(HanLP.tokenize(text))
#######################Native API#######################
# hanlp.load(save_dir: str, verbose=None, **kwargs)→ hanlp.common.component.Component
# 粗分标准(MSR,Microsoft Research)中文分词:适合文本挖掘业务
tok = hanlp.load(hanlp.pretrained.tok.COARSE_ELECTRA_SMALL_ZH)
print(tok(text))
# 细分标准(CTB,Chinese Treebank)中文分词:适合搜索引擎业务
tokFine = hanlp.load(hanlp.pretrained.tok.FINE_ELECTRA_SMALL_ZH)
tokFine.config.output_spans = True # 输出每个单词在文本中的原始位置
print(tokFine(text))
# 词性标注:词性标注任务的输入为已分词的一个或多个句子
tokens = tok(text)
pos = hanlp.load(hanlp.pretrained.pos.CTB9_POS_ELECTRA_SMALL)
print(pos(tokens))
# 命名实体识别:命名实体识别任务的输入为已分词的句子
ner = hanlp.load(hanlp.pretrained.ner.MSRA_NER_ELECTRA_SMALL_ZH)
print(ner(tokens))
说明:模型会在首次加载时(hanlp.load)自动下载到本地缓存(HANLP_HOME目录)。如果由于某些原因自动下载失败时,按照控制台提示从镜像站点手动下载一个zip文件到指定目录(无需解压)。
Text Processing
chardet
chardet是一个自动检测字符编码的Python库。
chardet - Python 2/3 compatible character encoding detector.
import chardet
print(chardet.detect(b'This is a test'))
print(chardet.detect('这是一个测试'.encode('gbk')))
print(chardet.detect('这是一个测试'.encode('utf-8')))
langid.py
langid.py - Stand-alone language identification system.
import langid
# (语言标识符, 置信度)
print(langid.classify("This is a test"))
print(langid.classify("这是一个测试"))
# 将概率转换为(0, 1)范围
identifier = langid.langid.LanguageIdentifier.from_modelstring(langid.langid.model, norm_probs=True)
print(identifier.classify("This is a test"))
print(identifier.classify("这是一个测试"))
langdetect
langdetect是Google语言检测库(language-detection)从Java到Python的重新实现。
Language detection library ported from Google's language-detection.
import langdetect
# 设置随机种子,保证输出一致
langdetect.DetectorFactory.seed = 0
# 最高的置信度
print(langdetect.detect("This is a test"))
print(langdetect.detect("这是一个测试"))
# 语言列表
print(langdetect.detect_langs("This is a test"))
print(langdetect.detect_langs("这是一个测试"))
fasttext
fastText is a library for efficient learning of word representations and sentence classification.
import fasttext
import os
modelPath = os.path.join(os.path.dirname(__file__), 'lid.176.bin')
model = fasttext.load_model(modelPath)
print(model.predict('This is a test', k=2))
print(model.predict('这是一个测试', k=2))
说明:如果通过pip install fasttext安装失败,可以从PyPI下载whl文件进行安装。
pypinyin
pypinyin是一个用于将汉字转换为拼音的Python库。
pypinyin - Convert Chinese hanzi (漢字) to pinyin (拼音).
import pypinyin
text = "中心"
print(pypinyin.pinyin(text))
print(pypinyin.lazy_pinyin(text))
# 启用多音字模式
print(pypinyin.pinyin(text, heteronym=True))
# 首字母风格
print(pypinyin.pinyin(text, style=pypinyin.Style.FIRST_LETTER))