You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Colab中使用Flair提取NER标签时遇AttributeError问题求助

Flair NER预测报错:AttributeError 解决方法

问题场景

在Colab中使用Flair提取文本NER标签时,调用tagger.predict(text)出现错误,具体信息如下:

原代码

from flair.data import Sentence
from flair.models import SequenceTagger

text = "Apple is headquartered in Cupertino, California."
tagger = SequenceTagger.load("flair/ner-english")

tagger.predict(text)

报错信息

2023-09-01 09:00:29,790 SequenceTagger predicts: Dictionary with 20 tags: <unk>, O, S-ORG, S-MISC, B-PER, E-PER, S-LOC, B-ORG, E-ORG, I-PER, S-PER, B-MISC, I-MISC, E-MISC, I-ORG, B-LOC, E-LOC, I-LOC, <START>, <STOP>
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-17-02be6f83cf90> in <cell line: 8>()
      6 
      7 
----> 8 tagger.predict(text)
      9 print(text)
     10 print('The following NER tags are found:')

1 frames
/usr/local/lib/python3.10/dist-packages/flair/models/sequence_tagger_model.py in predict(self, sentences, mini_batch_size, return_probabilities_for_all_classes, verbose, label_name, return_loss, embedding_storage_mode, force_token_predictions)
    454                 sentences = [sentences]
    455 
--> 456             Sentence.set_context_for_sentences(cast(List[Sentence], sentences))
    457 
    458             # filter empty sentences

/usr/local/lib/python3.10/dist-packages/flair/data.py in set_context_for_sentences(cls, sentences)
   1087         previous_sentence = None
   1088         for sentence in sentences:
-> 1089             if sentence.is_context_set():
   1090                 continue
   1091             sentence._previous_sentence = previous_sentence

AttributeError: 'str' object has no attribute 'is_context_set'

错误原因

Flair的tagger.predict()方法要求传入Flair框架定义的Sentence对象,而非原生字符串。原代码直接传递字符串变量text,导致方法内部试图调用字符串不存在的is_context_set()方法,触发AttributeError。

解决方法

将字符串转换为Flair的Sentence实例后,再传入predict()方法。修正后的完整代码如下:

from flair.data import Sentence
from flair.models import SequenceTagger

text = "Apple is headquartered in Cupertino, California."
# 将字符串转为Flair的Sentence对象
sentence = Sentence(text)
tagger = SequenceTagger.load("flair/ner-english")

# 传入Sentence对象执行预测
tagger.predict(sentence)

# 打印结果
print(sentence)
print('提取到的NER标签:')
for entity in sentence.get_spans('ner'):
    print(f"{entity.text} → {entity.tag}")

运行结果示例

Sentence: "Apple is headquartered in Cupertino , California ." → 8 Tokens
提取到的NER标签:
Apple → ORG
Cupertino → LOC
California → LOC

内容的提问来源于stack exchange,提问作者HanaKannan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 18:13:34