PS:目前中文支持并不好!!!!




简介

工业级自然语言处理。

特性:

  • 非破坏性标记
  • 命名实体识别
  • 支持55种以上语言
  • 11种语言的17个统计模型
  • 预训练词向量
  • 速度上的SOTA
  • 轻松整合深度学习
  • 词性标注
  • 标签依赖解析
  • 语法驱动的句子分段
  • 内置语法和NER的可视化
  • 方便string-to-hash映射
  • 导出到numpy数据数组
  • 高效二进制序列化
  • 简单的模型打包和部署
  • 稳健、严格评估的准确性




安装

pip install spacy
python -m spacy download en_core_web_sm




初试

import spacy

# 加载英文分词器、标注器、解析器、命名实体识别、词向量
nlp = spacy.load('zh_core_web_sm')

# 处理整个文档
text = 'When Sebastian Thrun started working on self-driving cars at Google in 2007, few people outside of the company took him seriously. “I can tell you very senior CEOs of major American car companies would shake my hand and turn away because I wasn’t worth talking to,” said Thrun, in an interview with Recode earlier this week.'
doc = nlp(text)

# 分析语法
print('名词短语:', [chunk.text for chunk in doc.noun_chunks])
print('动词:', [token.lemma_ for token in doc if token.pos_ == 'VERB'])

# 查找命名实体、短语和概念
for entity in doc.ents:
    print('实体:{} 标签:{}'.format(entity.text, entity.label_))

    
# 名词短语: ['Sebastian Thrun', 'self-driving cars', 'Google', 'few people', 'the company', 'him', 'I', 'you', 'very senior CEOs', 'major American car companies', 'my hand', 'I', 'Thrun', 'an interview', 'Recode']
# 动词: ['start', 'work', 'drive', 'take', 'can', 'tell', 'would', 'shake', 'turn', 'talk', 'say']
# 实体:Sebastian 标签:NORP
# 实体:Google 标签:ORG
# 实体:2007 标签:DATE
# 实体:American 标签:NORP
# 实体:Recode 标签:ORG
# 实体:earlier this week 标签:DATE




命名实体识别

类别 描述
PERSON 人,包括虚构
NORP 民族、宗教或政治团体
FAC 建筑物、机场、公路、桥梁等
ORG 公司、中介、事业单位等
GPE 国家、城市、州
LOC 地理地点、山脉、水体
PRODUCT 物品、车辆、食物等(不包括服务)
EVENT 以飓风、战役、战争、体育赛事等命名
WORK_OF_ART 书籍、歌曲等
LAW 制成法律的文件
LANGUAGE 任意语言
DATE 绝对或相对的日期或时期
TIME 比一天短的时间
PERCENT 百分比,包含%
MONEY 货币价值,包括单位
QUANTITY 度量,如重量或距离
ORDINAL 序数词,如第一第二
CARDINAL 数量词




中文支持

下载spaCy中文模型zh_core_web_sm-2.x.x.tar.gz

安装

pip install zh_core_web_sm-2.x.x.tar.gz

运行代码

import zh_core_web_sm

nlp = zh_core_web_sm.load()

doc = nlp("王小明在北京的清华大学读书")
for token in doc:
    print(token.text, token.lemma_, token.pos_, token.tag_, token.dep_, token.shape_, token.is_alpha, token.is_stop,
          token.has_vector, token.ent_iob_, token.ent_type_, token.vector_norm, token.is_oov)

能用的话恭喜你

不能用的话查看ValueError: could not broadcast input array from shape (128) into shape (96)

在这里插入图片描述




使用GPU

调用spacy.prefer_gpu()

import spacy

spacy.prefer_gpu()
nlp = spacy.load("en_core_web_sm")




参考文献

  1. spaCy · Industrial-strength Natural Language Processing in Python
  2. spaCy API Documentation
  3. spaCy2.1中文模型包
  4. 使用Spacy 进行自然语言处理
  5. SpaCy 中文模型
  6. 如何基于公开语料库构建spaCy中文模型
  7. displaCy Named Entity Visualizer
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐