【问题标题】:Stream a string into pygments lexer?将字符串流式传输到 pygments 词法分析器?
【发布时间】:2016-06-29 15:11:35
【问题描述】:

我想使用 pygments 即时为我突出显示代码 - 基本上是一个巨大的 JSON 对象列表。这是我尝试过的:

from pygments.lexers import JsonLexer
from pygments.formatters import HtmlFormatter
from pygments import highlight
import StringIO
f = StringIO.StringIO()
f.write('a')
f.seek(0)
print highlight(f, JsonLexer(), HtmlFormatter())

这给了我以下错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/d33tah/virtualenv/lib/python2.7/site-packages/pygments/__init__.py", line 87, in highlight
    return format(lex(code, lexer), formatter, outfile)
  File "/home/d33tah/virtualenv/lib/python2.7/site-packages/pygments/__init__.py", line 45, in lex
    return lexer.get_tokens(code)
  File "/home/d33tah/virtualenv/lib/python2.7/site-packages/pygments/lexer.py", line 151, in get_tokens
    text, _ = guess_decode(text)
  File "/home/d33tah/virtualenv/lib/python2.7/site-packages/pygments/util.py", line 309, in guess_decode
    text = text.decode('utf-8')
AttributeError: StringIO instance has no attribute 'decode'

显然这是错误的界面。什么是正确的?

【问题讨论】:

    标签: python json streaming syntax-highlighting pygments


    【解决方案1】:

    highlight 期望 f 是一个字符串,它有一个 decode 属性。 StringIO 没有那个属性。

    In [30]: type(f)
    Out[30]: instance
    
    In [31]: type(f.read())
    Out[31]: str
    

    只需使用直字符串即可。

    In [34]: pygments.highlight('a', lexer, formatter)
    Out[34]: u'<div class="highlight"><pre><span></span><span class="err">a</span>\n</pre></div>\n'
    

    【讨论】:

      猜你喜欢
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2010-10-21
      • 2018-11-29
      • 2012-07-09
      • 1970-01-01
      • 2020-10-02
      • 1970-01-01
      相关资源
      最近更新 更多