首页 > 解决方案 > 如何识别 prargraph 中存在 2 个不同的字符串

问题描述

我有 2 个不同的列表,其中包含名称和位置。需要在文本中识别名称和位置的位置。

输入

名称:['Mughal'] 地点:['Panipat','Agra']

text=['帕尼帕特战役奠定了阿格拉莫卧儿王朝的基础。']

输出:

开始位置:15;结束位置:21;字:Panipat;类型:位置;开始位置:50;结束位置:55;字:莫卧儿;类型:姓名

代码:

for t in (text):
for n in name_:
    while index_ < len(t):
        index_ = t.find(n,index_)
        if index_ == -1:
            break
        else:
            kwmatch.append((index_, index_+len(n),"Name"))
            index_  += len(rect) 
    index_ = 0
a = (text,{'entities':kwmatch})
doctuple.append(a)
kwmatch = []
a = None

标签: python-3.xtextspacy

解决方案


首先,如果您要使用字典(https://docs.python.org/3/tutorial/datastructures.html#dictionaries) ,保存您Name的数据会容易得多。例如Location

dct = {
    'Name'  : ['Mughal'],
    'Location':  ['Panipat','Agra']
}

之后,您可以遍历文本列表中的每个文本,使用string.find查找单词的开始和结束索引,并且可以从正在搜索的单词和键中获取单词和类型。

text=['The battle of Panipat laid the foundation of the Mughal dynasty in Agra.']

for t in text:
    for key, value in dct.items():
        for v in value:
            #Starting index using find
            start_pos = t.find(v)+1
            #Ending index after adding the length of word
            end_pos = start_pos+len(v)-1
            #Word and type are the word we are looking for, and the key of the dictionary
            print('Start position: {}; end position: {}; Word: {}; type: {}'.format(start_pos, end_pos, v, key))

然后输出出现。

Start position: 50; end position: 55; Word: Mughal; type: Name
Start position: 15; end position: 21; Word: Panipat; type: Location
Start position: 68; end position: 71; Word: Agra; type: Location

推荐阅读