D
D
Danil Polonsky2021-07-06 03:21:36
Python
Danil Polonsky, 2021-07-06 03:21:36

I want to extract the keywords from the text and 5 characters that are in front of them, how to do this?

I'm creating a program.. and I would like to know how to make it take a keyword from a certain text and what is in front of it, for example: ( text: hi man! how are you? ) the keyword hi and I want something else to be taken 5 characters before it (total: hi man) how to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
soremix, 2021-07-06
@EraFe

It is possible through the usual find, but it will need to be finalized for normal operation. It's better to take regex right away

import re

text = 'hi man! how are you?'
keyword = 'hi'

matched_string = re.search(rf'\b{keyword}\b.{{0,5}}', text)
if matched_string:
    matched_string = matched_string.group(0)

print(matched_string)

D
Developer, 2021-07-06
@samodum

regexp

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question