代码之家  ›  专栏  ›  技术社区  ›  tipu

在python中将html实体转换为它们的值

  •  2
  • tipu  · 技术社区  · 15 年前

    我在一些输入中使用这个正则表达式,

    [^a-zA-Z0-9@#]
    

    但是,这最终会删除输入中的许多html特殊字符,例如

    #227;, #1606;, #1588; (i had to remove the & prefix so that it wouldn't 
    show up as the actual value..)
    

    有没有方法可以将它们转换为它们的值,以便满足regexp表达式的要求?我也不知道为什么文本会这么大。

    3 回复  |  直到 15 年前
        1
  •  4
  •   Alex Martelli    15 年前

    鉴于您的文本似乎具有数字编码而非命名的实体,您可以首先将包含XML实体def(与号、哈希、数字、分号)的字节字符串转换为Unicode:

    import re
    xed_re = re.compile(r'&#(\d+);')
    def usub(m): return unichr(int(m.group(1)))
    
    s = 'ã, ن, ش'
    u = xed_re.sub(usub, s)
    

    如果终端仿真器可以显示任意Unicode标志符号,则 print u 然后将显示

    ã, ن, ش
    

    在任何情况下,如果您愿意,现在可以使用您的原始re,您不会意外地“捕获”实体,只有ascii字母、数字和您列出的两个标点符号。(我不确定这是您真正想要的——例如,为什么不使用重音字母,而只使用ascii字母呢?--但是,如果 你想要什么,它会起作用的)。

    如果你 除了数字编码的实体外,您还可以 应用 htmlentitydefs 另一个答案中推荐的标准库模块(不过,它只处理映射到拉丁语-1代码点的命名实体)。

        2
  •  1
  •   doublep    15 年前

    您可以调整以下脚本:

    import htmlentitydefs
    import re
    
    def substitute_entity (match):
        name = match.group (1)
        if name in htmlentitydefs.name2codepoint:
            return unichr (htmlentitydefs.name2codepoint[name])
        elif name.startswith ('#'):
            try:
                return unichr (int (name[1:]))
            except:
                pass
    
        return '?'
    
    print re.sub ('&(#?\\w+);', substitute_entity, 'x « y &wat; z {')
    

    在此处生成以下答案:

    x « y ? z {
    

    编辑:我把这个问题理解为“如何在进一步处理之前去掉html实体”,希望我没有浪费时间回答错误的问题;)

        3
  •  0
  •   Trey Hunner    15 年前

    如果不知道这个短语是用来做什么的,我就不能确切地告诉你需要什么。

    这将匹配特殊字符或字符串,不包括字母、数字、@和:

    [^a-zA-Z0-9@#]*|#[0-9A-Za-z]+;