Python:着色正则表达式匹配 [英] python: coloring regex matches
问题描述
我有一个简单的python脚本,在其中逐行读取文件:
I have a simple python script, where I read file line by line:
while True:
line = f.readline()
if line:
print line,
else:
time.sleep(0.1)
这些行除其他外包含 [IP地址]
和< email地址>
放在 []
和<>
中。
The lines contain, among other things, [IP addresses]
and <email addresses>
enclosed in []
and <>
.
我想正常打印整行,但是括号内的文本(即IP和电子邮件)以不同的颜色显示,例如'\033 [ 38; 5; 180m'
I would like to print the whole line normally, but have the text inside the brackets (i.e. IP and email) in different color, for instance '\033[38;5;180m'
最好的方法是什么?
我正在使用 python 2.7
推荐答案
我会安装一个自定义处理程序到 sys.stdout
,因此您不必担心更改现有代码- print
处理着色为了你。文本的实际替换可以通过几遍正则表达式完成。*
I would install a custom handler to sys.stdout
, so you don't need to worry about changing your existing code - print
handles colorizing for you. The actual replacement of text can be done with a couple passes of regex.*
import sys
import re
def colorize(text):
# Underline <email addresses>:
text = re.sub('<.*>',lambda m: '\x1b[4m{}\x1b[0m'.format(m.group()), text)
# Make [IP addresses] peach:
return re.sub('\[[0-9.]*\]',lambda m: '\x1b[38;5;180m{}\x1b[0m'.format(m.group()), text)
class MyStdout(object):
def __init__(self, term=sys.stdout):
self.term = term
def write(self, text):
text = colorize(text)
self.term.write(text)
sys.stdout = MyStdout()
print 'this is an email: <someone@whatever.com>'
print 'this is an ip: [1.1.1.1]'
这会强调电子邮件地址并制作出您所提供的桃红色IP。
This underlines email addresses and makes IPs that peach color you provided.
*在正则表达式上注。请注意与括号/ IP匹配的那个-我的原始实现中存在一个难以跟踪的错误,因为它与终端转义序列匹配。 uck!
*note on the regex. Be careful with the one that matches brackets/IPs - I had a hard-to-track-down bug in my original implementation because it was matching the terminal escape sequences. Yuck!
这篇关于Python:着色正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!