【问题标题】:stripping inline tags with python's lxml使用 python 的 lxml 去除内联标签
【发布时间】:2011-09-22 12:33:23
【问题描述】:

我必须处理 xml 文档中的两种内联标签。第一种类型的标签包含我想要保留的文本。我可以用 lxml 处理这个

etree.tostring(element, method="text", encoding='utf-8')

第二种类型的标签包含我不想保留的文本。我怎样才能摆脱这些标签和他们的文字?如果可能,我宁愿不使用正则表达式。

谢谢

【问题讨论】:

    标签: python xml tags lxml


    【解决方案1】:

    我认为 strip_tagsstrip_elements 在每种情况下都是您想要的。例如,这个脚本:

    from lxml import etree
    
    text = "<x>hello, <z>keep me</z> and <y>ignore me</y>, and here's some <y>more</y> text</x>"
    
    tree = etree.fromstring(text)
    
    print etree.tostring(tree, pretty_print=True)
    
    # Remove the <z> tags, but keep their contents:
    etree.strip_tags(tree, 'z')
    
    print '-' * 72
    print etree.tostring(tree, pretty_print=True)
    
    # Remove all the <y> tags including their contents:
    etree.strip_elements(tree, 'y', with_tail=False)
    
    print '-' * 72
    print etree.tostring(tree, pretty_print=True)
    

    ... 产生以下输出:

    <x>hello, <z>keep me</z> and <y>ignore me</y>, and
    here's some <y>more</y> text</x>
    
    ------------------------------------------------------------------------
    <x>hello, keep me and <y>ignore me</y>, and
    here's some <y>more</y> text</x>
    
    ------------------------------------------------------------------------
    <x>hello, keep me and , and
    here's some  text</x>
    

    【讨论】:

    • 非常感谢,这正是我想要的。
    • @Mark Longair:有没有办法使用strip_tags() 剥离所有子标签(并将子标签中的文本合并到父标签)?
    猜你喜欢
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    相关资源
    最近更新 更多