如何在 Span 上设置情绪属性?

How to set the sentiment attribute on a Span?

我正在尝试使用 spacy documentation 中的 Keras 示例,而不是像那样对 Doc 中的情绪分数求和

for sent, label in zip(sentences, ys):
  sent.doc.sentiment += label - 0.5

我想把分数保持在句子水平上

for sent, label in zip(sentences, ys):
  sent.sentiment = float(label)

这段代码给我那个错误

AttributeError: attribute 'sentiment' of 'spacy.tokens.span.Span' objects is not writable

是否有 setter 可以调用?我尝试 set_sentiment 没有成功。 我错过了什么吗?这是一个错误吗?

您可以找到 Span.sentiment here 的实现。你可以看到它确实是不可写的,因为它要么查找 self.doc.user_span_hooks 中的值,要么对该范围内的标记取 token.sentiment 的平均值。

[编辑如下]

Token 的情绪并不依赖于上下文。它使用基础 Lexeme 中存在的信息。这意味着任何词,例如 "love",在任何 sentence/context 中都具有相同的情感值。

所以你可以做两件事:要么像这样写词位的情绪:

vocab["love"].sentiment = 3.0

或者实现一个自定义挂钩,允许您定义任何您想要的功能。您可以在跨度 (doc.user_span_hooks) 或令牌 (doc.user_token_hooks) 级别执行此操作:

doc.user_span_hooks["sentiment"] = lambda span: 10.0