Python 找不到别名的Lexer
我正在尝试使用Pygments和Beauty Soup作为我为Google App Engine构建的博客软件的代码突出显示解决方案 它的工作原理是,我的HTML帖子将使用pre标记来识别代码。像这样:Python 找不到别名的Lexer,python,parsing,beautifulsoup,pygments,Python,Parsing,Beautifulsoup,Pygments,我正在尝试使用Pygments和Beauty Soup作为我为Google App Engine构建的博客软件的代码突出显示解决方案 它的工作原理是,我的HTML帖子将使用pre标记来识别代码。像这样: 看看这个很酷的代码示例 导入这个 def demo(): 通过 BeautifulSoup捕获pre标记之间的部分并将其传递给Pygments。Pygments应该检查类值并应用正确的lexar。Pygments然后应用格式并用格式文本替换原始文本。有关解决方案的详细说明,请参阅 错误 Cla
看看这个很酷的代码示例
导入这个
def demo():
通过
BeautifulSoup
捕获pre
标记之间的部分并将其传递给Pygments。Pygments应该检查类值并应用正确的lexar。Pygments然后应用格式并用格式文本替换原始文本。有关解决方案的详细说明,请参阅
错误
ClassNotFound:找不到别名[u'python']的lexer
也许我只是没有正确导入模块
代码
来自google.appengine.ext导入数据库
导入固定路径
进口bs4
导入pygments
从bs4导入BeautifulSoup
从pygments导入突出显示
从pygments.lexers导入按名称获取
从pygments.formatters导入HtmlFormatter
def格式化程序(p):
汤=美汤(p.otext)
preblocks=soup.findAll('pre')
对于预块中的预处理:
如果pre.具有_键(“类”):
代码=“”.join([unicode(项目)用于pre.contents中的项目])
代码=unescape\U html(代码)
lexer=lexers.get_lexer_by_name(pre['class'])
formatter=formatters.HtmlFormatter()
code_hl=突出显示(代码、lexer、格式化程序)
替换为(美化组(代码)
其他:
打印“禁止”
返回(汤)
追溯
是的,这就是问题所在。我没有导入脚本运行所需的库。这是正确的代码
import fix_path
import bs4
import pygments
from bs4 import BeautifulSoup
from pygments import highlight
from pygments import lexers
from pygments import formatters
def formatter(p):
soup = BeautifulSoup(p.otext)
preblocks = soup.findAll('pre')
for pre in preblocks:
if pre.has_key('class'):
code = ''.join([unicode(item) for item in pre.contents])
lexer = lexers.get_lexer_by_name("python")
formatter = formatters.HtmlFormatter()
code_hl = highlight(code, lexer, formatter)
pre.replaceWith(BeautifulSoup(code_hl))
return unicode(soup)
else:
return null
这是另一个问题
我想像这样动态地提取lexar名称
lexer = lexers.get_lexer_by_name(pre['class'])
但是,当我这样做时,我会得到以下错误
ClassNotFound: no lexer for alias [u'python'] found
如果我这样做
lexer = lexers.get_lexer_by_name("python")
它可以工作,但只适用于python。是的,这就是问题所在。我没有导入脚本运行所需的库。这是正确的代码
import fix_path
import bs4
import pygments
from bs4 import BeautifulSoup
from pygments import highlight
from pygments import lexers
from pygments import formatters
def formatter(p):
soup = BeautifulSoup(p.otext)
preblocks = soup.findAll('pre')
for pre in preblocks:
if pre.has_key('class'):
code = ''.join([unicode(item) for item in pre.contents])
lexer = lexers.get_lexer_by_name("python")
formatter = formatters.HtmlFormatter()
code_hl = highlight(code, lexer, formatter)
pre.replaceWith(BeautifulSoup(code_hl))
return unicode(soup)
else:
return null
这是另一个问题
我想像这样动态地提取lexar名称
lexer = lexers.get_lexer_by_name(pre['class'])
但是,当我这样做时,我会得到以下错误
ClassNotFound: no lexer for alias [u'python'] found
如果我这样做
lexer = lexers.get_lexer_by_name("python")
它可以工作,但只适用于python