【问题标题】:How to access span custom attributes with a variable name如何使用变量名访问跨度自定义属性
【发布时间】:2022-08-11 12:31:19
【问题描述】:

我正在使用 spacy 对文档中的自定义跨度进行分类。 然后我为每种跨度类型在跨度上创建自定义扩展。

文档的示例是:

from spacy.tokens import Span
city_getter = lambda span: any(city in span.text for city in ("New York", "Paris", "Berlin"))
Span.set_extension("has_city", getter=city_getter)
doc = nlp("I like New York in Autumn")
assert doc[1:4]._.has_city

想象一下,我有几个自定义扩展,我需要使用变量名内容访问扩展。

def dostuff(name_of_extension):
    *pseudocode:
    Loop over all the spans of the doc and see if the have the extension "name_of_extension" and extract some info
    return info


dostuff(name_of_extension="has_city")

这个想法是能够对不同的扩展使用相同的方法。

这里更一般的想法是如何访问 spacy 中的自定义定义属性

doc[1:4]._.X

其中 X 是一个变量。您可以想象,我想查看特定跨度是否 has_city 或 is_in_europe 或 is_on_the_cost 或其他。

Spacy Span API:https://spacy.io/api/token#attributes

【问题讨论】:

    标签: python spacy spacy-3


    【解决方案1】:

    这是一个关于如何按名称获取属性值的通用 Python 问题:

    getattr(doc[1:4]._, "has_city")
    

    【讨论】:

      猜你喜欢
      • 2016-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-01
      • 2018-05-31
      • 1970-01-01
      相关资源
      最近更新 更多