NLP Spacy增加了特殊情况以识别美元以外的货币(即CAD)



我正在做一项非常简单的任务,需要提取字符串中的美元金额。我试过Spacy,但它只识别1000美元而不是1000加元。我试着添加一个特殊情况

special_case = [{
'ORTH': 'CAD', 
'TAG': '$', 
'IS_CURRENCY': True}]
nlp.tokenizer.add_special_case('CAD', special_case)

运气不佳。

示例:

doc = nlp('I will pay you 1000 CAD tomorrow')
extracted_money = [ent.text for ent in doc.ents if ent.label_ == 'MONEY']

正在寻找返回我extracted_money =['1000 CAD']的解决方案

感谢您的帮助。

您可以使用spacy.matcher.Matcher:

import spacy
from spacy.matcher import Matcher
nlp = spacy.load("en_core_web_sm")
doc = nlp('I will pay you 1000 CAD tomorrow')
matcher = Matcher(nlp.vocab)  
pattern = [{'IS_DIGIT': True}, {'TEXT':'CAD'}] # NUMBER + CAD
matcher.add('CAD', [pattern])
matches = matcher(doc)
for match_id, start, end in matches:
string_id = nlp.vocab.strings[match_id]  # Get string representation
span = doc[start:end]  # The matched span
print( match_id, string_id, start, end, '->', span.text, '<-')

输出:

5189151114763691552 CAD 4 6 -> 1000 CAD <-

这里的模式是[{'IS_DIGIT': True}, {'TEXT':'CAD'}]:一个数字标记,后面跟一个CAD标记。

最新更新