Basic Pygments示例不起作用

时间:2016-05-07 12:57:57

标签: 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'

1 个答案:

答案 0 :(得分:0)

我知道已经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()))