擅长:python、mysql、java
<p>要给文本着色,可以使用ANSI转义码。在python中,您将执行以下操作来更改文本的颜色。在</p>
<pre><code>print '\033[' + str(code) + 'm'
</code></pre>
<p>其中code是来自<a href="http://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes" rel="nofollow">here</a>的值。请注意,0将重置任何更改,30-37是颜色。所以基本上你需要在匹配前插入'\033['+str(code)+'m',然后插入'\033[0m'来重置终端。例如,以下内容将导致打印终端的所有颜色:</p>
^{pr2}$
<p>下面是一个你所要求的混乱的例子</p>
<pre><code>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
</code></pre>