spacy教程(持续更新ing...)

诸神缄默不语-个人CSDN博文目录

最近更新时间:2022.6.27
最早更新时间:2022.6.27

本文介绍spacy模型的使用方式,即spacy的API使用教程。spacy包的API基本都要靠特定模型(trained pipeline)来使用,本文主要用英文(en_core_web_sm)和中文(zh_core_web_sm)来做示例,毕竟我就只会这两种语言。
spacy模型官网:Trained Models & Pipelines · spaCy Models Documentation

1. 分词

官网示例(可以在网上直接用docker运行):

import spacy
from spacy.lang.en.examples import sentences 

nlp = spacy.load("en_core_web_sm")
doc = nlp(sentences[0])
print(doc.text)
for token in doc:
    print(token.text, token.pos_, token.dep_)

输出:

Apple is looking at buying U.K. startup for $1 billion
Apple PROPN nsubj
is AUX aux
looking VERB ROOT
at ADP prep
buying VERB pcomp
U.K. PROPN dobj
startup NOUN advcl
for ADP prep
$ SYM quantmod
1 NUM compound
billion NUM pobj

可以看到模型将句子进行了tokenize,并给出了每个token的词性(pos_)和dependency relation(dep_)(我也不知道这是啥。介绍见:DependencyParser · spaCy API Documentation

2. 停用词表

Defaults文档见Language · spaCy API Documentation

import spacy
sp=spacy.load('en_core_web_sm')
StopWord=sp.Defaults.stop_words

StopWord是一个由停用词(字符串格式)组成的集合。

3. 分句

Sentencizer文档见Sentencizer · spaCy API Documentation
这里的句子是那种完整的句子,以句号之类的标准作为划分标准的那种。

import spacy
from spacy.lang.zh.examples import sentences

nlp = spacy.load("zh_core_web_sm")
total_doc=''.join(sentences)
nlp.add_pipe('sentencizer', name='sentence_segmenter', before='parser')
doc = nlp(total_doc)
print(doc.text)
for token in doc:
    print(token)
    print(token.is_sent_start)
for sent in doc.sents:
    print(sent)

输出略。总之is_sent_start属性为True的token就是句子开头的token,doc.sents是句子列表的迭代器。

另外v2.0版本spacy有这种分句的写法,在v3.0(我是3.2.4)版本的spacy中无法使用,我没有试过:

from seg.newline.segmenter import NewLineSegmenter  # note that pip package is called spacyss
import spacy

nlseg = NewLineSegmenter()

nlp = spacy.load('en')
nlp.add_pipe(nlseg.set_sent_starts, name='sentence_segmenter', before='parser')

doc = nlp(my_doc_text)

所需的包是:spacyss · PyPI

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

诸神缄默不语

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值