Skip to content

Instantly share code, notes, and snippets.

@dennissergeev
Created December 14, 2016 15:36
Show Gist options
  • Save dennissergeev/c15cf767633261702bee71976ab887c8 to your computer and use it in GitHub Desktop.
Save dennissergeev/c15cf767633261702bee71976ab887c8 to your computer and use it in GitHub Desktop.
"""
I will find you and I will highlight you
"""
from colorama import init, Fore, Style, Back
import re
init() # comment out if in Jupyter Notebook
def find_and_highlight(text, str_list, back=Back.YELLOW, fore=''):
regex_str = r'|'.join([r'({})'.format(s) for s in str_list])
regex = re.compile(regex_str, re.I)
i = 0; output = ''
for m in regex.finditer(text):
output += ''.join([text[i : m.start()],
fore, back,
text[m.start():m.end()],
Style.RESET_ALL])
i = m.end()
if not output:
print(text)
else:
print(''.join([output, text[m.end():]]))
if __name__ == '__main__':
words = ['never', 'gonna', 'give', 'you', 'up']
text = """Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you
"""
find_and_highlight(text, words)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment