0

I want to extract a word which is next to the keyword in the line. Note: The keyword exists twice in the line and I want to print both words next to the keyword.

Example:

This is my first Python language and I like this language to the most.

Desired Output:(need words next to language in below format)

and    
to 
ᴀʀᴍᴀɴ
  • 4,443
  • 8
  • 37
  • 57
Sai Kiran
  • 37
  • 5

3 Answers3

0

re.findall with zero-width positive lookbehind ((?<=language )) to match language before, then getting the desired substrings with \w+ and print-ing with sep='\n' to get desired output format:

In [33]: s = 'This is my first Python language and I like this language to the most.'

In [34]: print(*re.findall(r'(?<=language )\w+', s), sep='\n')
and   
to
heemayl
  • 39,294
  • 7
  • 70
  • 76
  • Hi, thanks. But it says invalid syntax for me when I execute – Sai Kiran Dec 26 '17 at 20:13
  • @SaiKiran What command did you run exactly? Add that to your question along with your `python` version. – heemayl Dec 26 '17 at 20:14
  • The same one which you gave me above. s = 'This is my first Python language and I like this language to the most.' print (*re.findall(r'(?<=language )\w+', s), sep='\n') – Sai Kiran Dec 26 '17 at 20:19
  • @SaiKiran If you're on Python 2: `print '\n'.join(re.findall(r'(?<=language )\w+', s))` – heemayl Dec 26 '17 at 20:21
0
data = 'This is my first Python language and I like this language to the most.'


for i, word in enumerate(data.split()):
    if word == 'language':
        print(data.split()[i + 1])
lpozo
  • 598
  • 2
  • 9
  • Thank you Sir, this is simple and I could get output as desired. – Sai Kiran Dec 26 '17 at 20:32
  • Thanks. Have a good day too... Sorry for late question: what does function ' enumerate ' do ? – Sai Kiran Dec 26 '17 at 20:44
  • I think this is what the code above is doing. Basically the data.split() is separating the string (text) by the spaces. If you print the data.split() you actually get a python list with separate entries for all the words. What enumerate does is it turns that list into an enumerate object. It is really a list containing tuples, looking like (counter, value). Here it is in a simpler form: data.split() = ['This', 'is', 'my','first'] enumerate(data.split()) = [('0','This'), ('1','is'), ('2','my'),('3','first')] – Ben10 Dec 26 '17 at 21:57
  • Or here is a link to an answer which has way better explaining then me: https://stackoverflow.com/a/22171593/8625593 – Ben10 Dec 26 '17 at 21:58
0
text = "hola esto es una prueba donde esto busca la siguiente linea de esto"
brk = "esto"
for i, texto in enumerate(text.split(brk)):
  if i > 0:
    print( texto.split()[0] if len(texto.split()) > 0 else '')

And now you just have to change the text and the break work