如何在Python中突出显示正则表达式匹配?

gui*_*ism 4 python editor

我如何在句子中突出显示正则表达式中的匹配?我想我可以使用匹配的位置,就像我从中得到的那样:

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)]
Run Code Online (Sandbox Code Playgroud)

但是如何强制终端在输出该字符串期间更改这些跨度的颜色?

Nic*_*ley 11

有几种终端颜色包可用,例如termstyletermcolor.我喜欢colorama,它也适用于Windows.

这是一个用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)
Run Code Online (Sandbox Code Playgroud)


Klo*_*erk 4

要为文本着色,您可以使用 ANSI 转义码。在 python 中,您可以执行以下操作来更改从该点开始的文本颜色。

print '\033[' + str(code) + 'm'
Run Code Online (Sandbox Code Playgroud)

其中 code 是来自此处的值。请注意,0 将重置任何更改,30-37 是颜色。所以基本上你想在比赛前插入 '\033[' + str(code) + 'm' 并在比赛后插入 '\033[0m' 以重置你的终端。例如,以下内容应该会打印终端的所有颜色:

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

以下是您要求的一个混乱的例子

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
Run Code Online (Sandbox Code Playgroud)