【问题标题】:NLP: Spacy custom rule based matchingNLP:基于 Spacy 自定义规则的匹配
【发布时间】:2022-08-14 21:45:54
【问题描述】:

我正在研究 spacy,需要从文本中找到一些信息,例如电子邮件、电话号码和多个值。下面是我的代码。但是,我在匹配器中做错了一些事情,因此我没有得到想要的输出。下面是代码。

import spacy
nlp = spacy.load(\"en_core_web_sm\")
from spacy.matcher import Matcher
matcher = Matcher(nlp.vocab)

my_pattern = [{\"LOWER\": \"email\"}, {\"LOWER\": \"phone\"}]
matcher.add(\'MyPattern\', [my_pattern])
my_text = \"email: kashif.jilani@sample.com, phone: 1234567\"
my_doc = nlp(my_text)
desired_matches = matcher(my_doc)

for match_id, start, end in desired_matches:
    string_id = nlp.vocab.strings[match_id]
    span = my_doc[start:end]
    print(span.text)

    标签: nlp spacy


    【解决方案1】:

    首先,您对模式的格式有疑问。格式必须是模式列表,模式是字典列表。
    按照您当前的模式,您需要更改:
    my_pattern = [{"LOWER": "email"}, {"LOWER": "phone"}]
    

    对此:

    my_pattern = [[{"LOWER": "email"}], [{"LOWER": "phone"}]]
    

    但是我相信您有问题,因为您在原始帖子中说要提取电子邮件和电话号码等信息,但您当前只提取电子邮件和电话这两个词。但是,您可以使用 spacy 令牌匹配器使用以下模式轻松地自动提取这些信息:

    my_pattern = [[{'LIKE_EMAIL': True}], [{'LIKE_NUM': True}]]
    

    现在,如果您更改该行,您的代码将如下所示:

    nlp = spacy.load("en_core_web_sm")
    from spacy.matcher import Matcher
    matcher = Matcher(nlp.vocab)
    
    my_pattern = [[{'LIKE_EMAIL': True}], [{'LIKE_NUM': True}]]
    matcher.add('MyPattern',my_pattern)
    my_text = "email: kashif.jilani@sample.com, phone: 1234567"
    my_doc = nlp(my_text)
    desired_matches = matcher(my_doc)
    
    for match_id, start, end in desired_matches:
        string_id = nlp.vocab.strings[match_id]
        span = my_doc[start:end]
        print(span.text)
    
    # output:
    # kashif.jilani@sample.com
    # 1234567
    

    您可以在此处了解有关基于规则的匹配的更多信息:Rule based Matching

    【讨论】:

      猜你喜欢
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      相关资源
      最近更新 更多