如何在Polyglot python库找到的实体的原始文本中获取索引?

2024-06-16 14:05:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在python的poplyglot库中找到的实体的原始文本中获取索引。你知道吗

    # Polyglot example NER
    from polyglot.text import Text
    text1 = u'Ik wil Ben mijn zoontje met de naam Ben ziek melden.'
    print(text1)
    ptext1 = Text(text1)
    print(ptext1.entities)
    for sent in ptext1.sentences:
        for entity in sent.entities:
          print(entity.tag, entity, entity.start, entity.end)

结果是: [I-PER(['Ben'])] I-PER['Ben']8 9号

所以问题是,如果这些块索引在原始句子中,我如何得到起始索引和结束索引?你知道吗


Tags: textin文本实体forpolyglotsententity
1条回答
网友
1楼 · 发布于 2024-06-16 14:05:58

刚刚为我的问题找到了一个解决方案(也许不是最好的,但现在可以了):

ptext1 = Text(text1) 
prevIndex = 0 
for sent in ptext1.sentences: 
    for entity in sent.entities: 
        print(entity.tag, entity, entity.start, entity.end) 
        currentIndex = ptext1.index(entity[0], prevIndex) 
        print('startindex={}, endindex={}'.format(currentIndex, currentIndex+len(entity[0]))) 
        prevIndex = currentIndex+len(entity[0]) 

这将提供原始字符串中实体的开始索引和结束索引。你知道吗

相关问题 更多 >