Начнем с того, что вам будет намного легче сохранить данные Name
и Location
, если вы будете использовать словари (https://docs.python.org/3/tutorial/datastructures.html#dictionaries). например
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