属性错误:“str”对象没有属性“is_context_set”

问题描述 投票:0回答:1

我正在尝试实现天赋来获取一段文本的ner标签(在colab中执行此操作)。尝试

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)
print(text)
print('The following NER tags are found:')

for entity in text.get_spans('ner'):
    print(entity)

这是我得到的:

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'
python machine-learning nlp named-entity-recognition flair
1个回答
0
投票

首先将文本转换为

Sentence
,以便底层代码可以访问必要的函数并修改句子对象。

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

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

tagger.predict(sentence ) # <---
print(sentence)
...
© www.soinside.com 2019 - 2024. All rights reserved.