【问题标题】:Extracting start and end indices of a token using spacy使用 spacy 提取令牌的开始和结束索引
【发布时间】:2023-02-01 05:22:22
【问题描述】:

我正在查看很多句子,并希望提取给定句子中单词的开始和结束索引。

例如,输入如下:

“这是一个以英语为母语的人用英语写的句子。”

我想要的是“英语”一词的跨度,在这种情况下是:(30,37) 和 (50, 57)。

注意:有人指出我这个答案 (Get position of word in sentence with spacy)

但是这个答案并不能解决我的问题。它可以帮助我获取令牌的起始字符而不是结束索引。

所有帮助表示赞赏

【问题讨论】:

标签: python python-3.x spacy


【解决方案1】:

您可以在纯 python 中使用 re 执行此操作:

s="This is a sentence written in english by a native English speaker."

import re
[(i.start(), i.end()) for i in re.finditer('ENGLISH', s.upper())]

#output
[(30, 37), (50, 57)]

你也可以在 spacy 中做:

import spacy
nlp=spacy.load("en_core_web_sm")
doc=nlp("This is a sentence written in english by a native English speaker.")
for ent in doc.ents:
    if ent.text.upper()=='ENGLISH':
      print(ent.start_char,ent.end_char)

【讨论】:

    【解决方案2】:

    使用您链接的答案中的想法,您可以做这样的事情

    from spacy.lang.en import English
    nlp = English()
    s = nlp("This is a sentence written in english by a native English speaker")
    boundaries = []
    for idx, i in enumerate(s[:-1]):
        if i.text.lower() == "english":
            boundaries.append((i.idx, s[idx+1].idx-1))
    

    【讨论】:

      【解决方案3】:

      您可以简单地使用 SpaCy 这样做,它不需要对最后一个标记进行任何检查(与@giovanni 的解决方案不同):

      def get_char_span(input_txt):
      
        doc = nlp(input_txt)
      
        for i, token in enumerate(doc):
          start_i = token.idx
          end_i = start_i + len(token.text)
      
          # token span and the token
          print(i, token)
          # character span
          print((start_i, end_i))
          # veryfying it in the original input_text
          print(input_txt[start_i:end_i])
      
      inp = "My name is X, what's your name?"
      get_char_span(inp)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-11
        • 1970-01-01
        • 2020-01-07
        • 2021-08-21
        相关资源
        最近更新 更多