How can I highlight regular expressions in Python?

How can I highlight regular expression matches in a sentence? I suggest that I could use the location of the matches, as I would get from this:

s = "This is a sentence where I talk about interesting stuff like sencha tea." spans = [m.span() for m in re.finditer(r'sen\w+', s)] 

But how to make the terminal change the colors of these spaces during the output of this line?

+4
source share
2 answers

For colored text, you can use ANSI cancel codes. In python, you should do the following to change the color of the text from now on.

 print '\033[' + str(code) + 'm' 

Here the code is the meaning here . Please note that 0 will reset any changes, and 30-37 will reset. So basically you want to insert '\ 033 [' + str (code) + 'm' before the match and '\ 033 [0m' after that to reset your terminal. For example, the following should print all terminal colors you print:

 print 'break'.join('\033[{0}mcolour\33[0m'.format(i) for i in range(30, 38)) 

Below is a dirty example of what you requested

 import re colourFormat = '\033[{0}m' colourStr = colourFormat.format(32) resetStr = colourFormat.format(0) s = "This is a sentence where I talk about interesting stuff like sencha tea." lastMatch = 0 formattedText = '' for match in re.finditer(r'sen\w+', s): start, end = match.span() formattedText += s[lastMatch: start] formattedText += colourStr formattedText += s[start: end] formattedText += resetStr lastMatch = end formattedText += s[lastMatch:] print formattedText 
+2
source

There are several color package packages, such as termstyle or termcolor . I like colorama , which also works with Windows.

Here is an example of what you want with colorama:

 from colorama import init, Fore import re init() # only necessary on Windows s = "This is a sentence where I talk about interesting stuff like sencha tea." print re.sub(r'(sen\w+)', Fore.RED + r'\1' + Fore.RESET, s) 
+10
source

All Articles