I want to find words that appear after a keyword (specified and searched by me) and print out the result. I know that i am suppose to use regex to do it, and i tried it out
Without using regex, you can
strip punctuation (consider making everything single case, including search term)
split your text into individual words
find index of searched word
get word from array (index + 1 for word after, index - 1 for word before )
Code snippet:
import string
s = 'hi my name is ryan, and i am new to python and would like to learn more'
t = 'name'
i = s.translate(string.maketrans("",""), string.punctuation).split().index(t)
print s.split()[i+1]
>> is
For multiple occurences, you need to save multiple indices:
import string
s = 'hi my NAME is ryan, and i am new to NAME python and would like to learn more'
t = 'NAME'
il = [i for i, x in enumerate(s.translate(string.maketrans("",""), string.punctuation).split()) if x == t]
print [s.split()[x+1] for x in il]
>> ['is', 'python']