编写自己的过滤器¶
在 0.7 版本加入.
编写自己的过滤器非常简单。你所要做的就是将 Filter 类并重写 filter 方法。另外,一个过滤器是用一些关键字参数实例化的,您可以使用这些参数来调整过滤器的行为。
子类化过滤器¶
作为一个例子,我们编写了一个过滤器来转换 Name.Function 令牌正常 Name 使输出不那么丰富多彩的标记。
from pygments.util import get_bool_opt
from pygments.token import Name
from pygments.filter import Filter
class UncolorFilter(Filter):
def __init__(self, **options):
Filter.__init__(self, **options)
self.class_too = get_bool_opt(options, 'classtoo')
def filter(self, lexer, stream):
for ttype, value in stream:
if ttype is Name.Function or (self.class_too and
ttype is Name.Class):
ttype = Name
yield ttype, value
一些关于 lexer 参数:这可能非常令人困惑,因为它不需要是lexer实例。如果使用 add_filter() 函数,该函数为过滤器注册lexer。那样的话 lexer 将引用已注册筛选器的lexer。它 can 用于访问传递给lexer的选项。因为它可能 None 如果你接触到那个箱子,你总是要检查它。
使用装饰器¶
您也可以使用 simplefilter 装饰师来自 pygments.filter 模块:
from pygments.util import get_bool_opt
from pygments.token import Name
from pygments.filter import simplefilter
@simplefilter
def uncolor(self, lexer, stream, options):
class_too = get_bool_opt(options, 'classtoo')
for ttype, value in stream:
if ttype is Name.Function or (class_too and
ttype is Name.Class):
ttype = Name
yield ttype, value
您可以通过调用 uncolor(classtoo=True) ,方法与您通过调用 UncolorFilter(classtoo=True) 。事实上,装饰者会自动确保 uncolor 是内部筛选器类的子类化的类。这个班级 uncolo 使用修饰函数作为筛选方法。(这就是为什么有一个 self 您可能最终不会在该方法中使用的参数。)