简体   繁体   中英

How to extract a word from the line which is next to particular keyword

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 

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
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])
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM