I am new to python and trying to solve this problem.
words = ['plus', 'Constantly', 'the']
string = "Plus, I Constantly adding new resources, guides, and the personality quizzes to help you travel beyond the Guidebook"
output: I adding Guidebook
here I want to match the list element to the string and get the next word from the string to construct a new word.
I tried to do it by splitting the word into list and check if they are in the list. But the 'Plus,' won't match because of the ',' and also there has two 'the' but I only need to get the last word after 'the'
CodePudding user response:
One way to do this is to use regex to split string
by words (the pattern used is [\w]
). Then you can build a dictionary of the pairs, so that you can look up the first word to retrieve the following word.
import re
words = ['plus', 'Constantly', 'the']
string = "Plus, I Constantly adding new resources, guides, and the personality quizzes to help you travel beyond the Guidebook"
string_splits = re.findall(r'[\w] ',string)
pairs = {x:y for x,y in zip(map(lambda x: x.lower(), string_splits), string_splits[1:])}
print(' '.join(pairs.get(word.lower()) for word in words))
Edit to expand the dict comprehsion;
pairs = {}
for x,y in zip(map(lambda x: x.lower(), string_splits), string_splits[1:]):
pairs[x] = y