首页 > 解决方案 > 给定一段文本标记位置文本

问题描述

我想看看是否有一个方便的python库可以接受一个字符串并返回代表一个位置的单词索引?

例如,输入文本“New York is a state in United States”

返回令牌

美国纽约

或它们各自在文本中的索引。

我想用它在我的网站中自动突出显示文本中的位置。

谢谢,拉利斯

标签: locationnltk

解决方案


SpaCy 是用于此任务的库。

您应该安装en_core_web_lg(最大的英文模型)以获得最佳的命名实体识别 (NER) 准确性。

然后运行以下代码来收集位置实体。

import spacy

nlp = spacy.load('en_core_web_lg')
text = "New York is a state in United States"
doc = nlp(text)
# GPE = Countries, cities, states, LOC = Non-GPE locations, mountain ranges, bodies of water
locations = [ent for ent in doc.ents if ent.label_ in ['GPE', 'LOC']] 
print(locations)

输出:

[New York, United States]

推荐阅读