Как вставить слова из предложения в список в правильном последовательном порядке - PullRequest
1 голос
/ 23 октября 2019

У меня есть строка / предложение:

text = 'Obama and Putin had a meeting today in Russia over lunch where they discussed the new green deal and the Paris agreement.'

И у меня есть два списка:

sentence_list = []
grouped_words = ['Obama and Putin', 'a meeting', 'today', 'Russia', 'lunch', 'the new green deal', 'the Paris agreement']

Как я могу добавить слова от grouped_words до sentence_list, затемдобавить слова из исходной строки text, которые НЕ равны словам в grouped_words sentence_list? Окончательный список будет выглядеть примерно так:

['Obama and Putin', 'had', 'a meeting', 'today', 'in','Russia', 'over', 'lunch','where', 'they','discussed', 'the','new green deal', 'and', 'the Paris agreement']

Этот список хранит содержимое grouped_words в том же порядке, что и исходная строка, при добавлении новых слов, которые были в строке, также в том же порядке. заказ.

Как мне получить список, похожий на этот?

Спасибо за помощь!

Ответы [ 2 ]

1 голос
/ 23 октября 2019

Не могу придумать причудливый вкладыш, так что вот простой способ петли:

text = 'Obama and Putin had a meeting today in Russia over lunch where they discussed the new green deal and the Paris agreement.'
sentence_list = []
grouped_words = ['Obama and Putin', 'a meeting', 'today', 'Russia', 'lunch', 'the new green deal', 'the Paris agreement']

for i in grouped_words:
    while True:
        if text.startswith(i):
            text = text.replace(i+" ","")
            sentence_list.append(i)
            break
        else:
            new = text.split()[0]
            sentence_list.append(new)
            text = text.replace(new+" ","")

print (sentence_list)

#['Obama and Putin', 'had', 'a meeting', 'today', 'in', 'Russia', 'over', 'lunch', 'where', 'they', 'discussed', 'the new green deal', 'and', 'the Paris agreement']
0 голосов
/ 23 октября 2019

Использует регулярное выражение для захвата подстроки между двумя другими подстроками из text и предполагает, что text начинается с первого слова в grouped_words. В другом случае вам нужно обработать эту часть.

import re

text = 'Obama and Putin had a meeting today in Russia over lunch where they discussed the new green deal and the Paris agreement.'
grouped_words = ['Obama and Putin', 'a meeting', 'today', 'Russia', 'lunch', 'the new green deal', 'the Paris agreement']

lst = [grouped_words[0]]
for x, y in zip(grouped_words, grouped_words[1:]):
    result = re.search(f'{x}(.*){y}', text)
    lst.extend([*result.group(1).strip().split(), y])

print(lst)
# ['Obama and Putin', 'had', 'a meeting', 'today', 'in','Russia', 'over', 'lunch','where', 'they','discussed', 'the','new green deal', 'and', 'the Paris agreement']
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...