【发布时间】:2014-03-20 12:29:45
【问题描述】:
我正在编写一个脚本来重构模板增强的 html。
我希望 beautifulsoup 逐字打印 {{ }} 中的任何代码,而不将 > 或其他符号转换为 html 实体。
需要将一个包含多个模板的文件拆分成多个文件,每个文件都有一个模板。
规格:splitTemplates templates.html templateDir 必须:
- 阅读templates.html
- 对于每个
<template name="xxx">contents {{ > directive }}</template>,将此模板写入文件templateDir/xxx
代码sn-p:
soup = bs4.BeautifulSoup(open(filename,"r"))
for t in soup.children:
if t.name=="template":
newfname = dirname+"/"+t["name"]+ext
f = open(newfname,"w")
# note f.write(t) fails as t is not a string -- prettify works
f.write(t.prettify())
f.close()
不良行为:
{{ &gt; directive }} 变为 {{ &gt; directive }} 但需要保留为 {{ &gt; directive }}
更新:f.write(t.prettify(formatter=None)) 有时会保留 &gt;,有时会将其更改为 &gt;。这似乎是最明显的变化,不知道为什么它会改变一些&gt; 而不是其他的。
已解决:感谢 Hai Vu 和 https://stackoverflow.com/a/663128/103081
import HTMLParser
U = HTMLParser.HTMLParser().unescape
soup = bs4.BeautifulSoup(open(filename,"r"))
for t in soup.children:
if t.name=="template":
newfname = dirname+"/"+t["name"]+ext
f = open(newfname,"w")
f.write(U(t.prettify(formatter=None)))
f.close()
【问题讨论】:
标签: python beautifulsoup handlebars.js