介绍

自然语言处理(NLP) 是人工智能方向一个非常重要的研究领域。 自然语言处理在很多智能应用中扮演着非常重要的角色,例如:

  • automated chat bots,
  • article summarizers,
  • multi-lingual translation
  • opinion identification from data

每一个利用NLP来理解非结构化文本数据的行业,不仅要求准确,而且在获取结果方面也很敏捷。

自然语言处理是一个非常广阔的领域,NLP 的任务包括

  • text classification,
  • entity detection,
  • machine translation,
  • question answering,
  • concept identification.

在本文中,将介绍一个高级的 NLP 库 - spaCy

内容列表

  1. 关于 spaCy 和 安装
  2. Spacy 流水线 和 属性
    1. Tokenization
    2. Pos Tagging
    3. Entity Detection
    4. Dependency Parsing
    5. 名词短语
  3. 与 NLTK 和 coreNLP 的对比

1.关于 spaCy 和 安装

1.1 关于 Spacy

Spacy 是由 cython 编写。因此它是一个非常快的库。 spaCy 提供简洁的接口用来访问其方法和属性 governed by trained machine (and deep) learning models.

1.2 安装

安装 Spacy

pip install spacy

下载数据和模型

python -m spacy download en

现在,您可以使用 Spacy 了。

2. Spacy 流水线 和 属性

要想使用 Spacy 和 访问其不同的 properties, 需要先创建 pipelines通过加载 模型 来创建一个 pipelineSpacy 提供了许多不同的 模型 , 模型中包含了 语言的信息- 词汇表,预训练的词向量,语法 和 实体。

下面将加载默认的模型- english-core-web

import spacy
nlp = spacy.load(“en”)

nlp 对象将要被用来创建文档,访问语言注释和不同的 nlp 属性。我们通过加载一个 文本文件 来创建一个 document 。这里使用的是从 tripadvisor's 网站上下载下来的 旅馆评论。

document = open(filename).read()
document = nlp(document)

现在,document 成为 spacy.english 模型的一部分,同时 document 也有一些 成员属性。可以通过 dir(document) 查看。

dir(document)
>> [..., 'user_span_hooks', 'user_token_hooks', 'vector', 'vector_norm', 'vocab']

document 包含大量的文档属性信息,包括 - tokens, token’s reference index, part of speech tags, entities, vectors, sentiment, vocabulary etc. 下面将介绍一下几个属性

2.1 Tokenization

"this is a sentence."
-> (tokenization)
>> ['this', 'is', 'a', 'sentence', '.']

Spacy 会先将文档 分解成句子,然后再 tokenize 。我们可以使用迭代来遍历整个文档。

# first token of the doc
document[0]
>> Nice# last token of the doc
document[len(document)-5]
>> boston # List of sentences of our doc
list(document.sents)
>> [ Nice place Better than some reviews give it credit for.,Overall, the rooms were a bit small but nice.,
...
Everything was clean, the view was wonderful and it is very well located (the Prudential Center makes shopping and eating easy and the T is nearby for jaunts out and about the city).]

2.2 Part of Speech Tagging (词性标注)

词性标注: word 的 动词/名词/… 属性。这些标注可以作为 文本特征 用到 information filtering, statistical models, 和 rule based parsing 中.

# get all tags
all_tags = {w.pos: w.pos_ for w in document}
>> {83: 'ADJ', 91: 'NOUN', 84: 'ADP', 89: 'DET', 99: 'VERB', 94: 'PRON', 96: 'PUNCT', 85: 'ADV', 88: 'CCONJ', 95: 'PROPN', 102: 'SPACE', 93: 'PART', 98: 'SYM', 92: 'NUM', 100: 'X', 90: 'INTJ'}# all tags of first sentence of our document
for word in list(document.sents)[0]:  print(word, word.tag_)
>> (Nice, 'JJ') (place, 'NN') (Better, 'JJR') (than, 'IN') (some, 'DT') (reviews, 'NNS') (give, 'VBP') (it, 'PRP') (credit, 'NN') (for, 'IN') (., '.')

下面代码创建一个 文本处理 操作,去掉噪声词。

#define some parameters
noisy_pos_tags = ["PROP"]
min_token_length = 2#Function to check if the token is a noise or not
def isNoise(token):     is_noise = Falseif token.pos_ in noisy_pos_tags:is_noise = True elif token.is_stop == True:is_noise = Trueelif len(token.string) <= min_token_length:is_noise = Truereturn is_noise
def cleanup(token, lower = True):if lower:token = token.lower()return token.strip()# top unigrams used in the reviews
from collections import Counter
cleaned_list = [cleanup(word.string) for word in document if not isNoise(word)]
Counter(cleaned_list) .most_common(5)
>> [('hotel', 683), ('room', 652), ('great', 300),  ('sheraton', 285), ('location', 271)]

2.3 Entity Detection (实体检测)

Spacy 包含了一个快速的 实体识别模型,它可以识别出文档中的 实体短语。有多种类型的实体,例如 - 人物,地点,组织,日期,数字。可以通过 documentents 属性来访问这些实体。

下面代码用来 找出 当前文档中的所有 命名实体。

labels = set([w.label_ for w in document.ents])
for label in labels: entities = [cleanup(e.string, lower=False) for e in document.ents if label==e.label_] entities = list(set(entities)) print label,entities

2.4 Dependency Parsing

spacy 一个非常强大的特性就是 十分快速和准确的语法解析树的构建,通过一个简单的 API 即可完成。这个 parser 也可以用作句子边界检测和短语切分。通过 “.children” , “.root”, “.ancestor” 即可访问。

# extract all review sentences that contains the term - hotel
hotel = [sent for sent in document.sents if 'hotel' in sent.string.lower()]# create dependency tree
sentence = hotel[2]
for word in sentence:print(word, ': ', str(list(word.children)))
>> A :  []
cab :  [A, from]
from :  [airport, to]
the :  []
airport :  [the]
to :  [hotel]
the :  []
hotel :  [the]
can :  []
be :  [cab, can, cheaper, .]
cheaper :  [than]
than :  [shuttles]
the :  []
shuttles :  [the, depending]
depending :  [time]
what :  []
time :  [what, of]
of :  [day]
the :  []
day :  [the, go]
you :  []
go :  [you]
. :  []

下面代码所作的工作是:解析所有 包含 “hotel” 句子的依赖树,看看都用了什么样的形容词来描述 “hotel”。下面创建了一个自定义函数来解析依赖树和抽取相关的词性标签。

# check all adjectives used with a word
def pos_words (document, token, pos_tag):sentences = [sent for sent in document.sents if token in sent.string]     pwrds = []for sent in sentences:for word in sent:if token in word.string: pwrds.extend([child.string.strip() for child in word.childrenif child.pos_ == pos_tag] )return Counter(pwrds).most_common(10)pos_words(document, 'hotel', "ADJ")
>> [(u'other', 20), (u'great', 10), (u'good', 7), (u'better', 6), (u'nice', 6), (u'different', 5), (u'many', 5), (u'best', 4), (u'my', 4), (u'wonderful', 3)]

2.5 Noun Phrases (名词短语)

Dependency trees 也可以用来生成名词短语。

# Generate Noun Phrases
doc = nlp(u'I love data science on analytics vidhya')
for np in doc.noun_chunks:print(np.text, np.root.dep_, np.root.head.text)
>> I nsubj lovedata science dobj loveanalytics pobj on

3.与CNTK和core NLP 的对比

参考资料

https://github.com/pytorch/text

https://www.analyticsvidhya.com/blog/2017/04/natural-language-processing-made-easy-using-spacy-%E2%80%8Bin-python/

使用 spacy 进行自然语言处理(一)相关推荐

  1. python如何下载安装spacy_使用 spacy 进行自然语言处理(一)

    介绍 自然语言处理(NLP) 是人工智能方向一个非常重要的研究领域. 自然语言处理在很多智能应用中扮演着非常重要的角色,例如:automated chat bots, article summariz ...

  2. spacy自然语言处理工具库--en_core_web_sm

    spaCy 是自然语言处理(NLP)任务的必备库.spaCy 处理文本的过程是模块化的, 当调用 NLP 处理文本时,spaCy 首先将文本标记化以生成 Doc 对象,然后,依次在几个不同的组件中处理 ...

  3. 开课吧:适合开发人工智能应用的编程语言有哪些?

    众所周知目前人工智能技术得到了广泛的应用,为人们的生活和工作提供了一定的便利,同时也促进了企业的发展,如果想要快速入门人工智能,不仅需要了解清楚人工智能技术,同时还需要明白适合开发人工智能应用的编程语 ...

  4. Paper:GPT之《Improving Language Understanding by Generative Pre-Training》翻译与解读

    Paper:GPT之<Improving Language Understanding by Generative Pre-Training>翻译与解读 目录 GPT之<Improv ...

  5. python 统计组合用什么库_盘点2018年热门Python库|TOP20

    来源:CDA数据分析师 在解决数据科学任务和挑战方面,Python继续处于领先地位.去年,我对当时热门的Python库进行了总结.今年,我在当中加入新的库,重新对2018年热门Python库进行全面盘 ...

  6. NLP之文本分词综述

    文本分词综述 文本分词 介绍 应用场景 常见算法 常用的分词库 代码demo jieba分词: 特点 流程 demo NLTK分词: 特点 流程 demo spaCy分词: 特点 流程 demo St ...

  7. 文本/文章相似度数据集及使用示例

    目录 1.一些文档相似性的数据集: 2.用于训练文章相似性模型的数据集: 3.要使用ArXiv数据集来训练文章相似性模型,可以遵循以下步骤: 1.一些文档相似性的数据集: Microsoft Rese ...

  8. 独家 | 快速掌握spacy在python中进行自然语言处理(附代码链接)

    作者:Paco Nathan 翻译:笪洁琼 校对:和中华 本文约6600字,建议阅读15分钟. 本文简要介绍了如何使用spaCy和Python中的相关库进行自然语言处理(有时称为"文本分析& ...

  9. 推荐 :快速掌握spacy在python中进行自然语言处理(附代码链接)

    作者:Paco Nathan 翻译:笪洁琼 校对:和中华 本文约6600字,建议阅读15分钟. 本文简要介绍了如何使用spaCy和Python中的相关库进行自然语言处理(有时称为"文本分析& ...

最新文章

  1. LinkedList 实现 Queue
  2. How to create DBFS file system
  3. SFB 项目经验-51-某上市企业2千人Exchange 2013升级2016高可用之伤01
  4. Ubuntu16.04 python2.7升级python3.5
  5. findbugs, checkstyle, pmd的myeclipse7.5+插件安装(转:http://blog.csdn.net/priestmoon/article/details/63941)
  6. robot1,Mechanical structure
  7. 第一章 计算机网络 1 计网体系结构的概念和功能 [计算机网络笔记]
  8. linux如何运行synaptic,Linux_Ubuntu 7.04 Synaptic软件包管理器功能,Ubuntu的新立得软件包管理器(Syn - phpStudy...
  9. Java设计模式学习总结(9)——结构型模式之过滤器模式(标准模式)
  10. 编程猫海龟编辑器python_编程猫海龟编辑器
  11. 【百度地图】——利用三级联动加载百度地图
  12. 51Nod1601 完全图的最小生成树计数 Trie Prufer编码
  13. 钉钉日志范文100篇_钉钉怎么添加日志模板 几步轻松添加
  14. [法国][无法触碰/触不可及][BD-RMVB.720p.中字][2011最新/法国票房冠军]
  15. Android接入三方登录——QQ、微信、Facebook、Twitter
  16. 计算机入门可以做什么工作,如何上好计算机入门课
  17. linux重命名文件或文件夹(mv命令 rename命令)
  18. 计算机毕业设计 移动设备的眼球追踪技术及其应用(源码+论文)
  19. 电力电子技术填空题(80+道),适合期末复习、面试等
  20. sap 服务器 拷贝文件,本文示例如何使用SAP FTP Function将文件从应用服务器传输到另外一个FTP服务器上。...

热门文章

  1. Debian11安装MySql8
  2. has leaked window com.android.internal.policy.impl.PhoneWindow解决(Dialog.cancel、dismiss、hide区别)
  3. jenkins + git+maven做持续集成
  4. 女人不适合做产品经理?
  5. Moment.js 文档
  6. pyppeteer 报 Execution context was destroyed, most likely because of a navigation
  7. 日历控件(bootstrap-datetimepicker.js)
  8. 新兴研究将如何更好地应对社会挑战?我们等你来共同探讨!
  9. 计算机二级是wpsoffice高级应用吗,考计算机二级ms office高级应用但是自己电脑上office软件都是wps 这和word ppt excel 软件有区别吗...
  10. 电源输出的Overshoot和Undershoot 测试