1 回答

TA貢獻1777條經驗 獲得超10個贊
使用 spacy 匹配與使用正則表達式匹配字符串的問題在于,使用 spacy 你[幾乎]永遠不會提前知道分詞器會對你的字符串做什么:
有空間:
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']
考慮到這一點,您可以編寫 2 個模式來獲取兩種格式:
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
添加回答
舉報