python - 基本 Pygments 示例不起作用

标签 python pygments

我正在使用 Python 2.7 和 Pygments。我尝试在他们的 webpage 上使用基本示例,但它已经过时了。即使我尽我所能更新它,它也不起作用。

from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import html

code = 'print "Hello World"'
lexer = get_lexer_by_name("python", stripall=True)
formatter = html.Formatter()
print highlight(code, lexer, formatter)

输出:

C:\Python27\python.exe C:/scripts/practice/PySnippets/foo.py
Traceback (most recent call last):
  File "C:/scripts/practice/PySnippets/foo.py", line 8, in <module>
    print highlight(code, lexer, formatter)
  File "C:\Python27\lib\site-packages\pygments\__init__.py", line 87, in highlight
    return format(lex(code, lexer), formatter, outfile)
  File "C:\Python27\lib\site-packages\pygments\__init__.py", line 66, in format
    formatter.format(tokens, realoutfile)
  File "C:\Python27\lib\site-packages\pygments\formatter.py", line 95, in format
    return self.format_unencoded(tokensource, outfile)
AttributeError: 'Formatter' object has no attribute 'format_unencoded'

最佳答案

我知道已经过去了 2 年,但我认为如果你现在按照 Pygments 上的示例进行操作,它应该可以工作。

from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter

code = 'print "Hello World"'
print(highlight(code, PythonLexer(), HtmlFormatter()))

关于python - 基本 Pygments 示例不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37088848/

相关文章:

syntax-highlighting - 任何用于 Mustache 模板语言的 Pygments 词法分析器?

python - 使用 BeautifulSoup 删除 Python 中不需要的标签

使用 Pigment 程序突出显示 python 语法

python - 从动态字典创建矩阵

python - ipython notebook 'run all cells'是同时执行还是顺序执行?

python - 词法分析器正则表达式 pygments g 代码

syntax - Latex:使用Minted包-如何包装文本(linebreaks = true)

css - pygments + Bootstrap : highlight shell code with dark background

python - 使用正则表达式将自定义日志文件解析为字典

python - pytest - 使用另一个插件的插件