Spaczz為Spacy提供了模糊的匹配和其他正則匹配功能。 SPACZZ的組件具有與Spacy對應物相似的API,而Spaczz Pipeline組件可以集成到Spacy管道中,可以將它們作為型號保存/加載。
當前,Fuzzy Matching與RapidFuzz的Fuzz模塊和Regex匹配的匹配器當前依賴於Regex庫。 Spaczz肯定會受到其他圖書館和資源的額外影響。有關更多詳細信息,請參見參考部分。
支持Spacy> = 3.0
SPACZZ已在Ubuntu,MacOS和Windows Server上進行了測試。
v0.6.0發行說明:
python<=3.11,>=3.7 ,以及rapidfuzz>=1.0.0 。"spaczz_"的支持預先剝奪可選的SpaczzRuler init參數。另外,很抱歉在沒有棄用周期的情況下執行此操作。Matcher.pipe方法。spaczz_span自定義屬性現在已刪除。請參閱ChangElog以獲取以前的發行說明。最終將移至讀取文檔頁面。
可以使用PIP安裝空格。
pip install spaczz SPACZZ的主要功能是FuzzyMatcher , RegexMatcher和“模糊” TokenMatcher ,其功能與Spacy的Matcher和PhraseMatcher類似,以及將SpaczzRuler集成到Spaczz匹配器中,將Spaczz Matchers整合到Spacy Pipcacy Piquine Compention與Spacy的EntityRuler類似。
模糊匹配器的基本用法類似於Spacy的PhraseMatcher ,除了它返回模糊比率和匹配模式以及匹配ID,啟動和最終信息,因此請確保在解開包裝結果時包含比例和模式的變量。
import spacy
from spaczz . matcher import FuzzyMatcher
nlp = spacy . blank ( "en" )
text = """Grint M Anderson created spaczz in his home at 555 Fake St,
Apt 5 in Nashv1le, TN 55555-1234 in the US.""" # Spelling errors intentional.
doc = nlp ( text )
matcher = FuzzyMatcher ( nlp . vocab )
matcher . add ( "NAME" , [ nlp ( "Grant Andersen" )])
matcher . add ( "GPE" , [ nlp ( "Nashville" )])
matches = matcher ( doc )
for match_id , start , end , ratio , pattern in matches :
print ( match_id , doc [ start : end ], ratio , pattern ) NAME Grint M Anderson 80 Grant Andersen
GPE Nashv1le 82 Nashville
與Spacy Matchers不同,Spaczz Matchers用Pure Python編寫。雖然他們必須在初始化過程中傳遞尖頂詞彙,但這純粹是為了一致性,因為Spaczz Matchers不使用當前使用Spacy Vocab。這就是為什麼上面的match_id只是字符串而不是像Spacy Matcher中的整數值。
Spaczz Matchers還可以通過回調函數利用匹配規則。這些匹配的回調需要接受匹配器本身,匹配器的DOC,比賽索引和匹配器產生的比賽。
import spacy
from spacy . tokens import Span
from spaczz . matcher import FuzzyMatcher
nlp = spacy . blank ( "en" )
text = """Grint M Anderson created spaczz in his home at 555 Fake St,
Apt 5 in Nashv1le, TN 55555-1234 in the US.""" # Spelling errors intentional.
doc = nlp ( text )
def add_name_ent ( matcher , doc , i , matches ):
"""Callback on match function. Adds "NAME" entities to doc."""
# Get the current match and create tuple of entity label, start and end.
# Append entity to the doc's entity. (Don't overwrite doc.ents!)
_match_id , start , end , _ratio , _pattern = matches [ i ]
entity = Span ( doc , start , end , label = "NAME" )
doc . ents += ( entity ,)
matcher = FuzzyMatcher ( nlp . vocab )
matcher . add ( "NAME" , [ nlp ( "Grant Andersen" )], on_match = add_name_ent )
matches = matcher ( doc )
for ent in doc . ents :
print (( ent . text , ent . start , ent . end , ent . label_ )) ('Grint M Anderson', 0, 3, 'NAME')
像Spacy的EntityRuler一樣, SpaczzRuler中已經實現了非常相似的實體更新邏輯。 SpaczzRuler還照顧處理重疊的比賽。在後面的部分中進行了討論。
與Spacy的匹配器不同,添加到Spaczz Matcher的規則具有可選的關鍵字參數,可以修改匹配行為。以下面的模糊匹配示例:
import spacy
from spaczz . matcher import FuzzyMatcher
nlp = spacy . blank ( "en" )
# Let's modify the order of the name in the text.
text = """Anderson, Grint created spaczz in his home at 555 Fake St,
Apt 5 in Nashv1le, TN 55555-1234 in the US.""" # Spelling errors intentional.
doc = nlp ( text )
matcher = FuzzyMatcher ( nlp . vocab )
matcher . add ( "NAME" , [ nlp ( "Grant Andersen" )])
matches = matcher ( doc )
# The default fuzzy matching settings will not find a match.
for match_id , start , end , ratio , pattern in matches :
print ( match_id , doc [ start : end ], ratio , pattern )接下來,我們更改“名稱”規則中模式的模糊匹配行為。
import spacy
from spaczz . matcher import FuzzyMatcher
nlp = spacy . blank ( "en" )
# Let's modify the order of the name in the text.
text = """Anderson, Grint created spaczz in his home at 555 Fake St,
Apt 5 in Nashv1le, TN 55555-1234 in the US.""" # Spelling errors intentional.
doc = nlp ( text )
matcher = FuzzyMatcher ( nlp . vocab )
matcher . add ( "NAME" , [ nlp ( "Grant Andersen" )], kwargs = [{ "fuzzy_func" : "token_sort" }])
matches = matcher ( doc )
# The default fuzzy matching settings will not find a match.
for match_id , start , end , ratio , pattern in matches :
print ( match_id , doc [ start : end ], ratio , pattern ) NAME Anderson, Grint 83 Grant Andersen
可用於模糊匹配設置的關鍵字參數的完整列表包括:
ignore_case (bool):是否在匹配之前要較低文本。默認是True 。min_r (INT):最小匹配比。thresh (INT):如果在初始掃描中超過此比率,並且flex > 0 ,則不會嘗試優化。如果flex == 0 , thresh無效。默認值為100 。fuzzy_func (str):使用模糊匹配功能的密鑰名稱。所有具有默認設置的RapidFuzz匹配功能都可以使用。用戶可以註冊其他模糊匹配功能。默認值是"simple" :"simple" = ratio"partial" = partial_ratio"token" = token_ratio"token_set" = token_set_ratio"token_sort" = token_sort_ratio"partial_token" = partial_token_ratio"partial_token_set" = partial_token_set_ratio"partial_token_sort" = partial_token_sort_ratio"weighted" = WRatio"quick" = QRatio"partial_alignment" = partial_ratio_alignment (需要rapidfuzz>=2.0.3 )flex (int |文字['默認值','min','max']):在優化期間,左右移動匹配邊界的令牌數。可以是最大len(pattern)和0分鐘的int (如果較高或更低的話,請警告和更改)。 "max" , "min"或"default"也有效。默認值為"default" : len(pattern) // 2 。min_r1 (int | none):對初始掃描過程中選擇所需的最小匹配比的可選顆粒控制。如果flex == 0 , min_r1將被min_r2覆蓋。如果flex > 0 ,則min_r1必須低於min_r2 ,並且通常“低”,因為匹配邊界最初不是彎曲的。默認值是None ,這將導致min_r1設置為round(min_r / 1.5) 。正則匹配器的基本用法也與Spacy的PhraseMatcher相當相似。它接受正則模式作為字符串,因此標誌必須是內聯的。將正則彙編與Regex軟件包一起編譯,因此支持近似的“模糊”匹配。為了提供對這些“模糊”匹配結果的訪問,匹配器返回計算出的模糊比率和匹配的模式,以及匹配ID,啟動和結束信息,因此請確保在解開結果時包括比率和圖案的變量。
import spacy
from spaczz . matcher import RegexMatcher
nlp = spacy . blank ( "en" )
text = """Anderson, Grint created spaczz in his home at 555 Fake St,
Apt 5 in Nashv1le, TN 55555-1234 in the US.""" # Spelling errors intentional.
doc = nlp ( text )
matcher = RegexMatcher ( nlp . vocab )
# Use inline flags for regex strings as needed
matcher . add (
"ZIP" ,
[ r"bd{5}(?:[-s]d{4})?b" ],
)
matcher . add ( "GPE" , [ r"(usa){d<=1}" ]) # Fuzzy regex.
matches = matcher ( doc )
for match_id , start , end , ratio , pattern in matches :
print ( match_id , doc [ start : end ], ratio , pattern ) ZIP 55555-1234 100 bd{5}(?:[-s]d{4})?b
GPE US 80 (usa){d<=1}
Spaczz Matchers還可以通過回調函數利用匹配規則。這些匹配的回調需要接受匹配器本身,匹配器的DOC,比賽索引和匹配器產生的比賽。有關詳細信息,請參見上面的模糊匹配器用法示例。
像模糊匹配器一樣,Regex Matcher具有可選的關鍵字參數,可以修改匹配行為。以下面的正則匹配示例。
import spacy
from spaczz . matcher import RegexMatcher
nlp = spacy . blank ( "en" )
text = """Anderson, Grint created spaczz in his home at 555 Fake St,
Apt 5 in Nashv1le, TN 55555-1234 in the USA.""" # Spelling errors intentional. Notice 'USA' here.
doc = nlp ( text )
matcher = RegexMatcher ( nlp . vocab )
# Use inline flags for regex strings as needed
matcher . add (
"STREET" , [ "street_addresses" ], kwargs = [{ "predef" : True }]
) # Use predefined regex by key name.
# Below will not expand partial matches to span boundaries.
matcher . add ( "GPE" , [ r"(?i)[U](nited|.?) ?[S](tates|.?)" ], kwargs = [{ "partial" : False }])
matches = matcher ( doc )
for match_id , start , end , ratio , pattern in matches :
print (
match_id , doc [ start : end ], ratio , pattern
) # comma in result isn't ideal - see "Roadmap" STREET 555 Fake St, 100 street_addresses
可用於正則匹配設置的關鍵字參數的完整列表包括:
ignore_case (bool):是否在匹配之前要較低文本。默認是True 。min_r (INT):最小匹配比。fuzzy_weights (str):正則插入,刪除和替代計數的加權方法的名稱。其他加權方法可以由用戶註冊。默認值為"indel" 。"indel" = (1, 1, 2)"lev" = (1, 1, 1)partial :( bool):是否應將部分匹配擴展到Token或Span doc的邊界。例如,正則態度僅匹配doc中的Token或Span的一部分。默認是True 。predef (字符串):是否應將正則弦字符串解釋為預定義的正則態度模式的鑰匙。用戶可以註冊其他預定義的正則態度模式。默認值為False."dates""times""phones""phones_with_exts""links""emails""ips""ipv6s""prices""hex_colors""credit_cards""btc_addresses""street_addresses""zip_codes""po_boxes""ssn_numbers"相似性匹配器的基本用法與Spacy的PhraseMatcher相似,除了它返回矢量相似性比和匹配模式以及匹配ID,啟動和最終信息,因此請確保在解開結果時將比率和模式包含變量。
為了從相似性匹配器中產生有意義的結果,必須使用帶有單詞向量的Spacy模型(Ex。Mediad或大型英語模型)來初始化匹配器,處理目標文檔並處理添加的任何模式。
import spacy
from spaczz . matcher import SimilarityMatcher
nlp = spacy . load ( "en_core_web_md" )
text = "I like apples, grapes and bananas."
doc = nlp ( text )
# lowering min_r2 from default of 75 to produce matches in this example
matcher = SimilarityMatcher ( nlp . vocab , min_r2 = 65 )
matcher . add ( "FRUIT" , [ nlp ( "fruit" )])
matches = matcher ( doc )
for match_id , start , end , ratio , pattern in matches :
print ( match_id , doc [ start : end ], ratio , pattern ) FRUIT apples 70 fruit
FRUIT grapes 73 fruit
FRUIT bananas 70 fruit
請注意,即使對於大多數純淨的python spaczz,此過程目前都非常慢,因此請注意應用程序的範圍。在SPACY中啟用GPU支持(請參見此處)應該有所提高速度,但我相信該過程仍將在純Python搜索算法中瓶頸瓶頸,直到我開發出更好的搜索算法和/或將搜索刪除到低級代碼(EX C)。
同樣,作為一個有點實驗性的功能,相似性匹配器當前並不是SpaczzRuler的一部分,也沒有單獨的標尺。如果您需要在Doc的實體中添加相似性匹配,則需要暫時使用匹配回調。請參閱上面的“模糊匹配器”匹配器示例以獲取想法。如果有足夠的興趣集成/創建與相似性匹配器的統治者,則可以做到。
可用於相似性匹配設置的關鍵字參數的完整列表包括:
ignore_case (bool):是否在模糊匹配之前要較低文本。默認是True 。min_r (INT):最小匹配比。thresh (INT):如果在初始掃描中超過此比率,並且flex > 0 ,則不會嘗試優化。如果flex == 0 , thresh無效。默認值為100 。flex (int |文字['默認值','min','max']):在優化期間,左右移動匹配邊界的令牌數。可以是最大len(pattern)和0分鐘的int (如果較高或更低的話,請警告和更改)。 "max" , "min"或"default"也有效。默認值為"default" : len(pattern) // 2 。min_r1 (int | none):對初始掃描過程中選擇所需的最小匹配比的可選顆粒控制。如果flex == 0 , min_r1將被min_r2覆蓋。如果flex > 0 ,則min_r1必須低於min_r2 ,並且通常“低”,因為匹配邊界最初不是彎曲的。默認值是None ,這將導致min_r1設置為round(min_r / 1.5) 。min_r2 (int | none):對匹配優化過程中選擇所需的最小匹配比的可選顆粒控制。通常需要高於min_r1和“高”,以確保僅返回質量匹配。默認值None ,這將導致min_r2設置為min_r 。注意:Spacy的Matcher現在支持模糊匹配,因此,除非您需要Spaczz的TokenMatcher中的特定功能,否則強烈建議使用Spacy更快的Matcher 。
令牌匹配器的基本用法類似於Spacy的Matcher 。它接受詞典列表的形式的標記模式,其中每個列表都描述了一個單個模式,每個詞典都描述了單個令牌。
令牌匹配器接受與Spacy對應物相同的所有令牌屬性和模式語法,但添加了模糊和模糊的regex支持。
"FUZZY"和"FREGEX"是另外兩個Spacy代幣模式選項。
例如:
[
{ "TEXT" : { "FREGEX" : "(database){e<=1}" }},
{ "LOWER" : { "FUZZY" : "access" , "MIN_R" : 85 , "FUZZY_FUNC" : "quick_lev" }},
]確保在圖案中使用大寫字典鍵。
可用於令牌匹配設置的關鍵參數的完整列表包括:
ignore_case (bool):是否在匹配之前要較低文本。只能設置為模式級別。用於“模糊”和“ fregex”模式。默認是True 。min_r (INT):最小匹配比。用於“模糊”和“ fregex”模式。fuzzy_func (str):使用模糊匹配功能的密鑰名稱。只能設置為模式級別。僅用於“模糊”模式。所有具有默認設置的RapidFuzz匹配功能都可以使用,但是任何基於令牌的功能都不提供單個令牌級別的實用程序。用戶可以註冊其他模糊匹配功能。包括和有用的功能是(默認值很simple ):"simple" = ratio"partial" = partial_ratio"quick" = QRatio"partial_alignment" = partial_ratio_alignment (需要rapidfuzz>=2.0.3 )fuzzy_weights (str):正則插入,刪除和替代計數的加權方法的名稱。其他加權方法可以由用戶註冊。默認值為"indel" 。"indel" = (1, 1, 2)"lev" = (1, 1, 1)predef :是否應將其解釋為預定義的正則態度模式的關鍵。只能設置為模式級別。僅適用於“ fregex”模式。默認值為False 。 import spacy
from spaczz . matcher import TokenMatcher
# Using model results like POS tagging in token patterns requires model that provides these.
nlp = spacy . load ( "en_core_web_md" )
text = """The manager gave me SQL databesE acess so now I can acces the Sequal DB.
My manager's name is Grfield"""
doc = nlp ( text )
matcher = TokenMatcher ( vocab = nlp . vocab )
matcher . add (
"DATA" ,
[
[
{ "TEXT" : "SQL" },
{ "LOWER" : { "FREGEX" : "(database){s<=1}" }},
{ "LOWER" : { "FUZZY" : "access" }},
],
[{ "TEXT" : { "FUZZY" : "Sequel" }, "POS" : "PROPN" }, { "LOWER" : "db" }],
],
)
matcher . add ( "NAME" , [[{ "TEXT" : { "FUZZY" : "Garfield" }}]])
matches = matcher ( doc )
for match_id , start , end , ratio , pattern in matches :
print ( match_id , doc [ start : end ], ratio , pattern ) DATA SQL databesE acess 91 [{"TEXT":"SQL"},{"LOWER":{"FREGEX":"(database){s<=1}"}},{"LOWER":{"FUZZY":"access"}}]
DATA Sequal DB 87 [{"TEXT":{"FUZZY":"Sequel"},"POS":"PROPN"},{"LOWER":"db"}]
NAME Grfield 93 [{"TEXT":{"FUZZY":"Garfield"}}]
即使令牌匹配器可能是Spacy的Matcher的替換,但如果您不需要Spaczz代幣匹配器的模糊功能,仍然建議使用Spacy的Matcher - 它會不必要地降低處理。
提醒:Spacy的Matcher現在支持模糊匹配,因此,除非您需要Spaczz的TokenMatcher中的特定功能,否則強烈建議使用Spacy的更快的Matcher 。
Spaczz Ruler將模糊和Regex短語匹配器以及“模糊”令牌匹配器結合到一個可以更新Doc.ents管道組件中。類似於Spacy的EntityRuler 。
必須以{label(str),模式(str或list),type(str),可選kwargs(dict)和可選ID(str)}格式的字典添加模式。
例如,模糊的短語模式:
{'label': 'ORG', 'pattern': 'Apple' 'kwargs': {'min_r2': 90}, 'type': 'fuzzy'}
或者,令牌模式:
{'label': 'ORG', 'pattern': [{'TEXT': {'FUZZY': 'Apple'}}], 'type': 'token'}
import spacy
from spaczz . pipeline import SpaczzRuler
nlp = spacy . blank ( "en" )
text = """Anderson, Grint created spaczz in his home at 555 Fake St,
Apt 5 in Nashv1le, TN 55555-1234 in the USA.
Some of his favorite bands are Converg and Protet the Zero.""" # Spelling errors intentional.
doc = nlp ( text )
patterns = [
{
"label" : "NAME" ,
"pattern" : "Grant Andersen" ,
"type" : "fuzzy" ,
"kwargs" : { "fuzzy_func" : "token_sort" },
},
{
"label" : "STREET" ,
"pattern" : "street_addresses" ,
"type" : "regex" ,
"kwargs" : { "predef" : True },
},
{ "label" : "GPE" , "pattern" : "Nashville" , "type" : "fuzzy" },
{
"label" : "ZIP" ,
"pattern" : r"b(?:55554){s<=1}(?:(?:[-s])?d{4}b)" ,
"type" : "regex" ,
}, # fuzzy regex
{ "label" : "GPE" , "pattern" : "(?i)[U](nited|.?) ?[S](tates|.?)" , "type" : "regex" },
{
"label" : "BAND" ,
"pattern" : [{ "LOWER" : { "FREGEX" : "(converge){e<=1}" }}],
"type" : "token" ,
},
{
"label" : "BAND" ,
"pattern" : [
{ "TEXT" : { "FUZZY" : "Protest" }},
{ "IS_STOP" : True },
{ "TEXT" : { "FUZZY" : "Hero" }},
],
"type" : "token" ,
},
]
ruler = SpaczzRuler ( nlp )
ruler . add_patterns ( patterns )
doc = ruler ( doc )
for ent in doc . ents :
print (
(
ent . text ,
ent . start ,
ent . end ,
ent . label_ ,
ent . _ . spaczz_ratio ,
ent . _ . spaczz_type ,
ent . _ . spaczz_pattern ,
)
) ('Anderson, Grint', 0, 3, 'NAME', 83, 'fuzzy', 'Grant Andersen')
('555 Fake St,', 9, 13, 'STREET', 100, 'regex', 'street_addresses')
('Nashv1le', 17, 18, 'GPE', 82, 'fuzzy', 'Nashville')
('55555-1234', 20, 23, 'ZIP', 90, 'regex', '\b(?:55554){s<=1}(?:(?:[-\s])?\d{4}\b)')
('USA', 25, 26, 'GPE', 100, 'regex', '(?i)[U](nited|\.?) ?[S](tates|\.?)')
('Converg', 34, 35, 'BAND', 93, 'token', '[{"LOWER":{"FREGEX":"(converge){e<=1}"}}]')
('Protet the Zero', 36, 39, 'BAND', 89, 'token', '[{"TEXT":{"FUZZY":"Protest"}},{"IS_STOP":true},{"TEXT":{"FUZZY":"Hero"}}]')
我們在上面的示例中看到我們引用了一些自定義屬性,這些屬性如下所述。
有關更多的SpaczzRuler示例,請參見此處。特別地,這提供了有關標尺的排序過程和模糊匹配參數的詳細信息。
SPACZZ導入時初始化一些自定義屬性。這些在Spacy的._.屬性並用spaczz_進一步填充,因此與您自己的自定義屬性不應發生衝突。如果有空位,將迫使它們覆蓋它們。
這些自定義屬性僅通過令牌級別的Spaczz標尺設置。這些屬性的跨度和DOC版本是引用令牌級屬性的Getters。
可用以下Token屬性。所有人都是可變的:
spaczz_token :默認值= False 。布爾值表示令牌是否是Spaczz Rouler設定的實體的一部分。spaczz_type :default = None 。字符串顯示了哪個匹配器使用令牌產生實體。spaczz_ratio :default = None 。如果令牌是匹配實體的一部分,它將返回模糊比率。spaczz_pattern :default = None 。如果令牌是匹配實體的一部分,則它將以產生匹配的字符串(用於令牌模式的JSON-Formatts)返回圖案。以下Span屬性引用跨度中包含的令牌屬性。所有人都是不變的:
spaczz_ent :default = False 。布爾值表示跨度中的所有令牌是否是Spaczz Rouler設定的實體的一部分。spaczz_type :default = None 。字符串表示使用包含令牌的哪些匹配器產生實體。spaczz_types :default = set() 。設置顯示哪些匹配器使用隨附的令牌生產實體。實體跨度應只有一種類型,但這允許您查看任何任意跨度中包含的類型。spaczz_ratio :default = None 。如果跨度中的所有令牌都是匹配實體的一部分,則它將返回模糊比率。spaczz_pattern :default = None 。如果跨度中的所有令牌都是匹配實體的一部分,則它將以產生匹配的字符串(用於令牌模式的JSON-Formatting)返回該模式。以下Doc屬性參考文檔中包含的令牌屬性。所有人都是不變的:
spaczz_doc :default = False 。布爾值表示文檔中是否有任何代幣是Spaczz Rouler設定的實體的一部分。spaczz_types :default = set() 。設置顯示哪些匹配者在文檔中產生了實體。SpaczzRuler具有自己的dout/trom vrom disk/bytes方法,並且將接受傳遞給spacy.load()的config參數。它還具有自己的Spacy工廠入口點,因此Spacy知道SpaczzRuler 。以下是用小型英語模型, EntityRuler和SpaczzRuler保存和加載Spacy管道的示例。
import spacy
from spaczz . pipeline import SpaczzRuler
nlp = spacy . load ( "en_core_web_md" )
text = """Anderson, Grint created spaczz in his home at 555 Fake St,
Apt 5 in Nashv1le, TN 55555-1234 in the USA.
Some of his favorite bands are Converg and Protet the Zero.""" # Spelling errors intentional.
doc = nlp ( text )
for ent in doc . ents :
print (( ent . text , ent . start , ent . end , ent . label_ )) ('Anderson, Grint', 0, 3, 'ORG')
('555', 9, 10, 'CARDINAL')
('Apt 5', 14, 16, 'PRODUCT')
('Nashv1le', 17, 18, 'GPE')
('TN 55555-1234', 19, 23, 'ORG')
('USA', 25, 26, 'GPE')
('Converg', 34, 35, 'PERSON')
('Zero', 38, 39, 'CARDINAL')
儘管Spacy在此示例中做出了不錯的工作來識別命名實體存在,但我們肯定可以改善匹配項 - 尤其是在應用標籤的類型中。
讓我們為某些基於規則的匹配添加一個實體標尺。
from spacy . pipeline import EntityRuler
entity_ruler = nlp . add_pipe ( "entity_ruler" , before = "ner" ) #spaCy v3 syntax
entity_ruler . add_patterns (
[{ "label" : "GPE" , "pattern" : "Nashville" }, { "label" : "GPE" , "pattern" : "TN" }]
)
doc = nlp ( text )
for ent in doc . ents :
print (( ent . text , ent . start , ent . end , ent . label_ )) ('Anderson, Grint', 0, 3, 'ORG')
('555', 9, 10, 'CARDINAL')
('Apt 5', 14, 16, 'PRODUCT')
('Nashv1le', 17, 18, 'GPE')
('TN', 19, 20, 'GPE')
('USA', 25, 26, 'GPE')
('Converg', 34, 35, 'PERSON')
('Zero', 38, 39, 'CARDINAL')
我們正在取得進步,但是納什維爾在文本中拼寫錯誤,因此實體統治者沒有找到它,我們仍然有其他實體可以修復/查找。
讓我們添加一個空格尺子以將這條管道弄清楚。我們還將在結果中包括spaczz_span自定義屬性,以表示通過SPACZZ設置的實體。
spaczz_ruler = nlp . add_pipe ( "spaczz_ruler" , before = "ner" ) #spaCy v3 syntax
spaczz_ruler . add_patterns (
[
{
"label" : "NAME" ,
"pattern" : "Grant Andersen" ,
"type" : "fuzzy" ,
"kwargs" : { "fuzzy_func" : "token_sort" },
},
{
"label" : "STREET" ,
"pattern" : "street_addresses" ,
"type" : "regex" ,
"kwargs" : { "predef" : True },
},
{ "label" : "GPE" , "pattern" : "Nashville" , "type" : "fuzzy" },
{
"label" : "ZIP" ,
"pattern" : r"b(?:55554){s<=1}(?:[-s]d{4})?b" ,
"type" : "regex" ,
}, # fuzzy regex
{
"label" : "BAND" ,
"pattern" : [{ "LOWER" : { "FREGEX" : "(converge){e<=1}" }}],
"type" : "token" ,
},
{
"label" : "BAND" ,
"pattern" : [
{ "TEXT" : { "FUZZY" : "Protest" }},
{ "IS_STOP" : True },
{ "TEXT" : { "FUZZY" : "Hero" }},
],
"type" : "token" ,
},
]
)
doc = nlp ( text )
for ent in doc . ents :
print (( ent . text , ent . start , ent . end , ent . label_ , ent . _ . spaczz_ent )) ('Anderson, Grint', 0, 3, 'NAME', True)
('555 Fake St,', 9, 13, 'STREET', True)
('Apt 5', 14, 16, 'PRODUCT', False)
('Nashv1le', 17, 18, 'GPE', True)
('TN', 19, 20, 'GPE', False)
('55555-1234', 20, 23, 'ZIP', True)
('USA', 25, 26, 'GPE', False)
('Converg', 34, 35, 'BAND', True)
('Protet the Zero', 36, 39, 'BAND', True)
驚人的!小型英語模型仍然犯了一個命名的實體識別錯誤(“ apt 5”中的“ 5”為CARDINAL ),但總體而言我們很滿意。
讓我們將此管道保存到磁盤上,並確保我們可以正確加載它。
import tempfile
with tempfile . TemporaryDirectory () as tmp_dir :
nlp . to_disk ( f" { tmp_dir } /example_pipeline" )
nlp = spacy . load ( f" { tmp_dir } /example_pipeline" )
nlp . pipe_names ['tok2vec',
'tagger',
'parser',
'attribute_ruler',
'lemmatizer',
'entity_ruler',
'spaczz_ruler',
'ner']
我們甚至可以確保仍然存在所有的空位尺圖案。
spaczz_ruler = nlp . get_pipe ( "spaczz_ruler" )
spaczz_ruler . patterns [{'label': 'NAME',
'pattern': 'Grant Andersen',
'type': 'fuzzy',
'kwargs': {'fuzzy_func': 'token_sort'}},
{'label': 'GPE', 'pattern': 'Nashville', 'type': 'fuzzy'},
{'label': 'STREET',
'pattern': 'street_addresses',
'type': 'regex',
'kwargs': {'predef': True}},
{'label': 'ZIP',
'pattern': '\b(?:55554){s<=1}(?:[-\s]\d{4})?\b',
'type': 'regex'},
{'label': 'BAND',
'pattern': [{'LOWER': {'FREGEX': '(converge){e<=1}'}}],
'type': 'token'},
{'label': 'BAND',
'pattern': [{'TEXT': {'FUZZY': 'Protest'}},
{'IS_STOP': True},
{'TEXT': {'FUZZY': 'Hero'}}],
'type': 'token'}]
Spaczz速度較慢的主要原因是,其名稱中的C不像SpaC Y中的大寫。 Spaczz用Pure Python編寫,它的匹配器當前不使用Spacy語言詞彙,這意味著遵循邏輯的人對於熟悉Python的人來說應該很容易。但是,這意味著SPACZZ組件的運行速度較慢,並且可能比其Spacy對應物更長的內存,尤其是隨著添加更多模式並且文檔越來越長的時間。因此,建議將諸如EntityRuler之類的Spacy組件用於幾乎不確定性的實體,例如一致的拼寫錯誤。當沒有可行的替代方案時,請使用空格組件。
我目前尚未致力於對Spaczz的性能優化,但是歡迎算法和優化建議。
加速FuzzyMatcher和SimilarityMatcher的主要方法是通過將flex參數降低到0 ,或者如果flex > 0 ,將min_r1參數增加到min_r2的值和/或降低thresh參數對min_r2值。請注意,所有這些“加速”都以可能改善比賽的機會成本。
如SimilarityMatcher描述中所述,使用GPU也可能有助於加快其匹配過程。
我總是很開放且能夠接受請求,但請注意,因為一個有很多東西可以學習的獨奏,開發的發展速度很慢。以下是我的Spaczz路線圖,因此您可以看到提出的問題可能適合我當前的優先事項。
注意:雖然我想保持spaczz的功能,但我並沒有積極開發它。我試圖響應問題和請求,但該項目目前不是我的重點。
優先級
增強
歡迎拉動請求和貢獻者。
SPACZZ用薄片覆蓋,配以黑色格式,並用Mypy進行了檢查(儘管這可以從改進的特異性中受益),並用pytest進行了測試,用NOX自動化,並用詩歌構建/包裝。 noxfile.py中還有其他一些開發工具以及GIT預先承諾的掛鉤。
為了促進Spaczz的開發,將存儲庫分配,然後安裝Spaczz及其與詩歌的開發依賴關係。如果您有興趣成為定期貢獻者,請直接與我聯繫。
poetry install # Within spaczz's root directory.作為我的Python工具鏈環境的一部分,我將NOX和預先投入在詩歌環境之外。在安裝預先任務的情況下,您可能還需要運行以下來提交更改。
pre - commit install唯一無法通過詩歌安裝的軟件包,而是用於測試和文檔示例的示例,是Spacy Medium Medine Model( en-core-web-md )。這將需要單獨安裝。下面的命令應解決問題:
poetry run python - m spacy download "en_core_web_md"