1 回答

TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超10個(gè)贊
使用 spacy 匹配與使用正則表達(dá)式匹配字符串的問題在于,使用 spacy 你[幾乎]永遠(yuǎn)不會(huì)提前知道分詞器會(huì)對你的字符串做什么:
有空間:
doc = nlp("This is my telephone number (0) 20 111 2222")
[tok.text for tok in doc]
['This', 'is', 'my', 'telephone', 'number', '(', '0', ')', '20', '111', '2222']
沒有空格:
doc = nlp("This is my telephone number (0)20 111 2222")
[tok.text for tok in doc]
['This', 'is', 'my', 'telephone', 'number', '(', '0)20', '111', '2222']
考慮到這一點(diǎn),您可以編寫 2 個(gè)模式來獲取兩種格式:
doc = nlp("My telephone number is either (0)20 111 2222 or (0) 20 111 2222")
matcher = Matcher(nlp.vocab, validate=True)
pattern1 = [ {'ORTH': '('}, {'SHAPE': 'd'},
{'ORTH': ')'},
{'SHAPE': 'dd'},
{'ORTH': '-', 'OP': '?'},
{'SHAPE': 'ddd'},
{'ORTH': '-', 'OP': '?'},
{'SHAPE': 'dddd'}]
pattern2 = [ {'ORTH': '('},
{'TEXT':{'REGEX':'[\d]\)[\d]*'}},
{'ORTH': '-', 'OP': '?'},
{'SHAPE': 'ddd'},
{'ORTH': '-', 'OP': '?'},
{'SHAPE': 'dddd'}]
matcher.add('PHONE_NUMBER_E', None, pattern1, pattern2)
matches = matcher(doc)
for match_id, start, end in matches:
string_id = nlp.vocab.strings[match_id]
span = doc[start:end]
print(span)
(0)20 111 2222
(0) 20 111 2222
添加回答
舉報(bào)