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