轻松的HTML和XHTML转录
cs.html的Python项目详细描述
格式错误的标记正在激怒。因此,当我必须生成html时,我使用自然的python对象(字符串、列表、dict)构造一个令牌结构,并使用这个模块将它们转录成语法正确的html。这也避免了大量繁琐且容易出错的实体转义。
此方案中的“令牌”是:
- 字符串:安全地转录到html,例如“some text here”
- int或float:安全地转录成html,如1或2.5。
- 序列:html标记:元素0是标记名,元素1(如果是映射)是元素属性,任何其他元素都是封闭的标记,例如:['h1',{'align':'center'},'heading text']
- 因为像“&foo”这样的字符串将其“&;”转录到实体“&;amp;”中,所以标记以“&;”开头的单个元素列表对实体进行编码,例如:[“<;”]
- 具有.tag(字符串)和.attrs(映射)属性的预成型标记对象
核心功能:
- transcribe(*tokens):生成包含html的字符串的生成器
- xtranscribe(*tokens):生成包含xhtml的字符串的生成器
- attrquote(s):根据html 4.01第3.2.2节,引用字符串s作为标记属性使用
- nbsp(s):将s转换为非中断文本:生成器生成包含转换为&;nbsp;实体的空白标记
便利程序:
- transcribe_s(*tokens):将tokens转换为包含html的字符串
- xtranscribe_s(*tokens):将tokens转换为包含xhtml的字符串
过时:
- tok2s:将令牌转录为字符串;puttok的简单包装器
- puttok:将令牌转录到文件中
- text2s:将字符串转录为html安全字符串;puttext的简单包装器
- puttext:将字符串作为html安全文本转录到文件中
示例:
from cs.html import transcribe, transcribe_s, xtranscribe, puttok [...] table = ['TABLE', {'width': '80%'}, ['TR', ['TD', 'a truism'], ['TD', '1 < 2'] ] ['TR', ['TD', 'a couple'], ['TD', 'A & B'] ] ] prose_with_table = [ 'Here is a line with a line break.', ['BR'], 'Here is a trite table:', table, ] [...] print('Here is the table's HTML:', transcribe_s(table)) [...] # write HTML tokens to a file for s in transcribe(['H1', {'align': 'left'}, 'Prose'], *prose_with_table): fp.write(s) [...] # write XHTML tokens to a file for s in xtranscribe(*prose_with_table): fp.write(s)