как идентифицировать 2 разные строки в праграфе - PullRequest
0 голосов
/ 20 апреля 2019

У меня есть 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

Ответы [ 2 ]

0 голосов
/ 22 апреля 2019

Начнем с того, что вам будет намного легче сохранить данные 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
0 голосов
/ 20 апреля 2019

Предполагая, что ваши списки Location и Name содержат элементы в строчных строках.

Попробуйте это:

#initialize your lists Location and Name here
Location = ['panipat', 'agra']
Name = ['mughal']

#initialize input_string with your string text
input_string = "The battle of Panipat laid the foundation of the Mughal dynasty in Agra"

#Position counter
pos=0

#output
ans=""

for i in input_string.split():
  if i.lower() in Location:
    ans += ("Start position: " + str(pos) + ";end position: " + str(pos+len(i)) + ";Word: " + str(i) + ";type: Location")
    pos+=len(i)
  elif i.lower() in Name:
    ans += ("Start position: " + str(pos) + ";end position: " + str(pos+len(i)) + ";Word: " + str(i) + ";type: Name")
    pos+=len(i)
  else:
    pass

print(ans)

Вы ничего не сказали о специальных персонажах. Если строка должна содержать их, вы можете очистить ее (см. здесь ) перед запуском вышеуказанного цикла for.

...