How can I highlight regex matches in Python?
How might I highlight the matches in regex in the sentence? I figure that I could use the locations of the matches like 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 do I force the terminal to change the colors of those spans during the output of that str开发者_如何学JAVAing?
There are several terminal color packages available such as termstyle or termcolor. I like colorama, which works on Windows as well.
Here's an example of doing 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))
To colour text you can use ANSI Escape codes. In python you would do the following to change the colour of the text from that point onwards.
print '\033[' + str(code) + 'm'
Where code is a value from here. Note that 0 will reset any changes, and 30-37 are colours. So basically you want to insert '\033[' + str(code) + 'm' before a match and '\033[0m' afterwards to reset your terminal. For example the following should result in all of your terminal's colours being printed:
print 'break'.join('\033[{0}mcolour\33[0m'.format(i) for i in range(30, 38))
The following is a messy example of what you asked for
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
精彩评论