pygmentsの出力したhtmlにスタイルを埋め込む
ここでソース張っても色とかつけるのが大変なので、pygmentsのhtml出力とcssを結合するスクリプトを書いてみた。
embedstyle.py
import sys
from xml.etree.ElementTree import ElementTree
import cssutils
from cssutils.css import CSSRule
css = cssutils.parseFile(sys.argv[2])
rules = dict([(x.selectorText, x.style.cssText.replace('\n', '')) for x in css.cssRules if x.type == CSSRule.STYLE_RULE])
tree = ElementTree(file=open(sys.argv[1]))
for elem in tree.getiterator():
c = elem.get('class', None)
if c:
style = rules.get('.'+c, None)
if style:
elem.attrib['style'] = style
tree.write(sys.stdout)
使用例
スタイル生成→HTML出力→結合
pygmentize -f html -S colorful > test.csspygmentize -o embedstyle.html embedstyle.py
python embedstyle.py pkglist.html test.css > out.html
これで出力したのがこのページのコード