- 基本上所有的
NLP
的任務(wù)都可以完成催首,是一個(gè)不得不學(xué)的庫隅茎。
Spacy功能簡介
可以用于進(jìn)行分詞广恢,命名實(shí)體識別,詞性識別等等馋没,但是首先需要下載預(yù)訓(xùn)練模型
pip install --user spacy
python -m spacy download en_core_web_sm
pip install neuralcoref
pip install textacy
sentencizer
- 將文章切分成句子昔逗,原理是
Spacy
通過將文章中某些單詞的is_sent_start
屬性設(shè)置為True
,來實(shí)現(xiàn)對文章的句子的切分篷朵,這些特殊的單詞在規(guī)則上對應(yīng)于句子的開頭勾怒。
import spacy
nlp = spacy.load('en_core_web_sm')# 加載預(yù)訓(xùn)練模型
txt = "some text read from one paper ..."
doc = nlp(txt)
for sent in doc.sents:
print(sent)
print('#'*50)
- 我在對
Latex
文件切分的時(shí)候,發(fā)現(xiàn)$.
和}.
中的句點(diǎn)不能被正確識別為句子的結(jié)尾声旺。當(dāng)一個(gè)語句最后出現(xiàn)數(shù)學(xué)表達(dá)式笔链,會有$.
模式。當(dāng)一個(gè)語句結(jié)尾出現(xiàn)引用文獻(xiàn)腮猖,會出現(xiàn)}.
模式鉴扫。為了讓Spacy
將這兩種模式識別為句子結(jié)尾,我們需要判斷$.
或}.
是否出現(xiàn)在某個(gè)單詞中澈缺,如果出現(xiàn)坪创,就將其后面一個(gè)單詞的is_sent_start
屬性設(shè)置成True
炕婶,代表新語句的開始。此外莱预,需要將這個(gè)定制的語句邊界函數(shù)添加切僅添加一次到spacy
的通道中柠掂。此后再使用nlp(text).sents
即可得到正確的句子切分。
def set_custom_boundaries(doc):
'''spacy does not set $. and }. as end of sentence.
This custom boundary will fix that bug. '''
for token in doc[:-1]:
if "$." in token.text or "}." in token.text or token.text == ";":
doc[token.i+1].is_sent_start = True
return doc
#add custom boundary once, skip if already exist
try:
nlp.add_pipe(set_custom_boundaries, before="parser")
except:
pass
Tokenization
將句子切分成單詞依沮,英文中一般使用空格分隔
import spacy
nlp = spacy.load('en_core_web_sm')
txt = "A magnetic monopole is a hypothetical elementary particle."
doc = nlp(txt)
tokens = [token for token in doc]
print(tokens)
Part-of-speech tagging
- 詞性標(biāo)注涯贞,標(biāo)注句子中每個(gè)單詞的詞性,是名詞動(dòng)詞還是形容詞悉抵。
pos = [token.pos_ for token in doc]
print(pos)
>>> ['DET', 'ADJ', 'NOUN', 'VERB', 'DET', 'ADJ', 'ADJ', 'NOUN', 'PUNCT']
# 對應(yīng)于中文是 【冠詞肩狂,形容詞,名詞姥饰,動(dòng)詞,冠詞孝治,形容詞列粪,形容詞,名詞谈飒,標(biāo)點(diǎn)】
# 原始句子是 [A, magnetic, monopole, is, a, hypothetical, elementary, particle, .]
Lemmatization
- 找到單詞的原型岂座,即詞性還原,將
am, is, are, have been
還原成be
杭措,復(fù)數(shù)還原成單數(shù)(cats -> cat)
费什,過去時(shí)態(tài)還原成現(xiàn)在時(shí)態(tài)(had -> have)
。在代碼中使用token.lemma_
提取
lem = [token.lemma_ for token in doc]
print(lem)
>>> ['a', 'magnetic', 'monopole', 'be', 'a', 'hypothetical', 'elementary', 'particle', '.']
Stop words
- 識別停用詞手素,
a,the
等等鸳址。
stop_words = [token.is_stop for token in doc]
print(stop_words)
>>> [True, False, False, True, True, False, False, False, False]
# 可以看到,這個(gè)磁單極的例子中停用詞有 a 和 is泉懦。
Dependency Parsing
依存分析稿黍,標(biāo)記單詞是主語,謂語崩哩,賓語還是連接詞巡球。程序中使用 token.dep_
提取。
dep = [token.dep_ for token in doc]
print(dep)
>>> ['det', 'amod', 'nsubj', 'ROOT', 'det', 'amod', 'amod', 'attr', 'punct']
-
Spacy
的依存分析采用了ClearNLP
的依存分析標(biāo)簽 ClearNLP Dependency Labels邓嘹。根據(jù)這個(gè)網(wǎng)站提供的標(biāo)簽字典酣栈,翻譯成人話:[限定詞, 形容詞修飾, 名詞主語汹押, 根節(jié)點(diǎn), 限定詞, 形容詞修飾, 形容詞修飾, 屬性, 標(biāo)點(diǎn)]
Noun Chunks
- 提取名詞短語矿筝,程序中使用
doc.noun_chunks
獲取。
noun_chunks = [nc for nc in doc.noun_chunks]
print(noun_chunks)
>>> [A magnetic monopole, a hypothetical elementary particle]
Named Entity Recognization
- 命名實(shí)體識別鲸阻,識別人名跋涣,地名缨睡,組織機(jī)構(gòu)名,日期陈辱,時(shí)間奖年,金額,事件沛贪,產(chǎn)品等等陋守。程序中使用
doc.ents
獲取。
txt = ''''European authorities fined Google a record $5.1 billion
on Wednesday for abusing its power in the mobile phone market and
ordered the company to alter its practices'
'''
doc = nlp(txt)
ners = [(ent.text, ent.label_) for ent in doc.ents]
print(ners)
>>> [('European', 'NORP'), ('Google', 'ORG'), ('$5.1 billion', 'MONEY'), ('Wednesday', 'DATE')]
-
更詳細(xì)的命名實(shí)體簡寫列表利赋。
Coreference Resolution
- 指代消解 水评,尋找句子中代詞
he
,she
媚送,it
所對應(yīng)的實(shí)體中燥。為了使用這個(gè)模塊,需要使用神經(jīng)網(wǎng)絡(luò)預(yù)訓(xùn)練的指代消解系數(shù)塘偎,如果前面沒有安裝疗涉,可運(yùn)行命令:pip install neuralcoref
txt = "My sister has a son and she loves him."
# 將預(yù)訓(xùn)練的神經(jīng)網(wǎng)絡(luò)指代消解加入到spacy的管道中
import neuralcoref
neuralcoref.add_to_pipe(nlp)
doc = nlp(txt)
doc._.coref_clusters
>>> [My sister: [My sister, she], a son: [a son, him]]
Display
可視化。把這條功能單獨(dú)列出來吟秩,是因?yàn)樗崃嗽劭邸Ee幾個(gè)簡單的例子,第一個(gè)例子是對依存分析的可視化涵防,
txt = '''In particle physics, a magnetic monopole is a
hypothetical elementary particle.'''
displacy.render(nlp(txt), style='dep', jupyter=True,\
options = {'distance': 90})
- 第二個(gè)例子是對命名實(shí)體識別的可視化
from spacy import displacy
displacy.render(doc, style='ent', jupyter=True)
知識提取
這一部分使用了 textacy, 需要通過pip命令進(jìn)行安裝闹伪,textacy.extract 里面的 semistructured_statements() 函數(shù)可以提取主語是 Magnetic Monopole,謂語原型是 be 的所有事實(shí)壮池。首先將維基百科上的關(guān)于磁單極的這篇介紹的文字拷貝到 magneti_monopole.txt 中偏瓤。
import textacy.extract
nlp = spacy.load('en_core_web_sm')
with open("magnetic_monopole.txt", "r") as fin:
txt = fin.read()
doc = nlp(txt)
statements = textacy.extract.semistructured_statements(doc, "monopole")
for statement in statements:
subject, verb, fact = statement
print(f" - {fact}")
- 如果搜索Magnetic Monopole, 輸出只有第三條,如果搜索 monopole, 結(jié)果如下:
- a singular solution of Maxwell's equation (because it requires removing the worldline from spacetime
- a [[topological defect]] in a compact U(1) gauge theory
- a new [[elementary particle]], and would violate [[Gauss's law for magnetism