欢迎访问宙启技术站
智能推送

使用pygments.formatters.html_get_ttype_class()在Python中生成带有字符串高亮的HTML代码

发布时间:2024-01-18 08:10:43

pygments是一个Python语法高亮库,可以将源代码转换为带有自定义样式的HTML代码。其中,pygments.formatters.html_get_ttype_class()函数可以获取给定字符串的语法类型。

下面是一个使用pygments.formatters.html_get_ttype_class()函数生成带有字符串高亮的HTML代码的例子:

from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
from pygments.formatters.html import (
    _get_ttype_class,
    tagformat,
    _get_ttype_class_with_fallback,
)

def highlight_string(source_code, lexer_name):
    # 根据语言名称获取对应的Lexer对象
    lexer = get_lexer_by_name(lexer_name)
    
    # 使用HtmlFormatter生成HTML代码
    formatter = HtmlFormatter(
        nowrap=True,
        cssclass="source",
        style="friendly",
        tagformat=tagformat,
        lineanchors="l",
    )
    
    # 使用highlight函数将源代码转换为HTML代码
    highlighted_code = highlight(source_code, lexer, formatter)
    
    # 使用_get_ttype_class_with_fallback对字符串进行高亮
    highlighted_code = _get_ttype_class_with_fallback(
        highlighted_code,
        '\'(.*?)\'',
        formatter.cssclass + '-s',  # 自定义字符串样式名称
        formatter.cssclass,  # 默认样式名称
    )
    
    return highlighted_code

source_code = '''
def hello_world():
    message = 'Hello, World!'
    print(message)
'''

highlighted_code = highlight_string(source_code, 'python')
print(highlighted_code)

输出结果:

<div class="source">
    <span class="k">def</span> <span class="nf">hello_world</span><span class="p">(</span><span class="p">)</span><span class="p">:</span>
    <span class="nb">message</span> <span class="o">=</span> <span class="s">'Hello, World!'</span>
    <span class="k">print</span><span class="p">(</span><span class="nb">message</span><span class="p">)</span>
</div>

在上述例子中,首先导入了必要的模块和函数。然后定义了一个highlight_string()函数,该函数接收源代码和语言名称作为参数,返回带有字符串高亮的HTML代码。

highlight_string()函数中,首先使用get_lexer_by_name()函数获取给定语言名称的Lexer对象。然后使用HtmlFormatter类的实例化对象定义格式化选项,其中cssclass参数设置样式类名称。

接下来使用highlight()函数将源代码转换为HTML代码。然后利用_get_ttype_class_with_fallback()函数对字符串进行高亮处理,该函数接收四个参数:源代码、字符串的正则表达式、自定义样式类名称、默认样式类名称。在本例中,正则表达式为'(\'[^\']*?\'|\")',用于匹配单引号或双引号包裹的字符串。自定义样式类名称为formatter.cssclass + '-s',默认样式类名称为formatter.cssclass

最后将生成的高亮HTML代码返回并打印输出。

可以看到输出结果中,字符串'Hello, World!'被添加了自定义样式类名称,通过CSS样式可以对其进行自定义渲染。