2014-02-19 13 views
1

我正在制作一个脚本来重构模板增强的html。制作美丽的汤玩弄手柄吧

我想beautifulsoup打印内部{{}}一字不差的任何代码,而无需转换>或其他符号转换为HTML实体。

它需要将具有多个模板的文件拆分为多个文件,每个文件都有一个模板。

规格:splitTemplates templates.html templateDir必须:

  1. 阅读templates.html
  2. 每个<template name="xxx">contents {{ > directive }}</template>,写这个模板文件templateDir/xxx

代码片段:

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() 

意外的行为:

{{ > directive }}变得{{ &gt; directive }}但需要保存为{{ > directive }}

更新:f.write(t.prettify(formatter=None))有时保留>,有时它变成&gt;。这似乎是最明显的变化,不知道为什么它改变了一些>而不是其他。

解决:由于海武也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() 

另请参见:https://gist.github.com/DrPaulBrewer/9104465

回答