python – 将HTML列表(>)转换为制表符(即缩进)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 将HTML列表(>)转换为制表符(即缩进),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2305字,纯文字阅读大概需要4分钟。
内容图文
![python – 将HTML列表(>)转换为制表符(即缩进)](/upload/InfoBanner/zyjiaocheng/731/3ad8ab6c4255402b9b326adecfb6041a.jpg)
曾经使用过几十种语言,但对Python来说是新手.
这是我的第一个(也许是第二个)问题,所以要温柔……
试图有效地将类似HTML的降价文本转换为wiki格式(特别是Linux Tomboy / GNote注释到Zim)并且一直停留在转换列表上.
对于像这样的2级无序列表……
>第一级
>第二级
Tomboy / GNote使用类似……
< list>< list-item>第一级< list>< list-item>第二级< / list-item>< / list>< / list-item>< / list>
但是,Zim个人维基希望这样……
* First level
* Second level
…带有前导标签.
我已经探索了regex模块函数re.sub(),re.match(),re.search()等,并发现了很酷的Python能力,可以将重复文本编码为……
count * "text"
因此,看起来应该有办法做某事……
newnote = re.sub("<list>", LEVEL * "\t", oldnote)
其中LEVEL是< list>的序数(出现).在笔记中.因此,对于第一个< list>,它将为0.遇到,1为第二,等
然后每次减少LEVEL< / list>遇到了.
<列表项>标签转换为项目符号的星号(在适当的前面加上换行符)和< / list-item>标签掉了.
最后……问题……
>如何获取LEVEL的值并将其用作制表符倍增器?
解决方法:
您应该使用xml解析器来执行此操作,但要回答您的问题:
import re
def next_tag(s, tag):
i = -1
while True:
try:
i = s.index(tag, i+1)
except ValueError:
return
yield i
a = "<list><list-item>First level<list><list-item>Second level</list-item></list></list-item></list>"
a = a.replace("<list-item>", "* ")
for LEVEL, ind in enumerate(next_tag(a, "<list>")):
a = re.sub("<list>", "\n" + LEVEL * "\t", a, 1)
a = a.replace("</list-item>", "")
a = a.replace("</list>", "")
print a
这将适用于您的示例,仅适用于您的示例.使用XML解析器.你可以使用xml.dom.minidom(它包含在Python中(至少2.7),不需要下载任何东西):
import xml.dom.minidom
def parseList(el, lvl=0):
txt = ""
indent = "\t" * (lvl)
for item in el.childNodes:
# These are the <list-item>s: They can have text and nested <list> tag
for subitem in item.childNodes:
if subitem.nodeType is xml.dom.minidom.Element.TEXT_NODE:
# This is the text before the next <list> tag
txt += "\n" + indent + "* " + subitem.nodeValue
else:
# This is the next list tag, its indent level is incremented
txt += parseList(subitem, lvl=lvl+1)
return txt
def parseXML(s):
doc = xml.dom.minidom.parseString(s)
return parseList(doc.firstChild)
a = "<list><list-item>First level<list><list-item>Second level</list-item><list-item>Second level 2<list><list-item>Third level</list-item></list></list-item></list></list-item></list>"
print parseXML(a)
输出:
* First level
* Second level
* Second level 2
* Third level
内容总结
以上是互联网集市为您收集整理的python – 将HTML列表(>)转换为制表符(即缩进)全部内容,希望文章能够帮你解决python – 将HTML列表(>)转换为制表符(即缩进)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。