UNESCAPE HTML实体

本文介绍了如何使用UNESCAPE HTML实体,这个概念源于弗雷德里克Lundh的开发工作,对于前端开发者尤其有用,可以帮助理解和处理HTML编码。
摘要由CSDN通过智能技术生成

这段代码可能对某些人有用,

ef parsefile(path):

   try:

      file = open(path, "r")

      fileread = file.read()

      fileread = unescape(fileread.decode('utf-8')).encode('utf-8')

      file.close()

   except:

      print "Reading File Bug"

      sys.exit(1)

   return ET.fromstring(fileread)

该吃UNESCAPE HTML实体程序已于弗雷德里克Lundh开发网站上找到。

def unescape(text):

   """Removes HTML or XML character references

      and entities from a text string.

      keep &,& gt; &ltin the source code.

   from Fredrik Lundh

   http://effbot.org/zone/re-sub.htm#unescape-html

   """

   def fixup(m):

      text = m.group(0)

      if text[:2] == "&#":

         # character reference

         try:

            if text[:3] == "&#x":

               return unichr(int(text[3:-1], 16))

            else:

               return unichr(int(text[2:-1]))

         except ValueError:

            print "erreur de valeur"

            pass

      else:

         # named entity

         try:

            if text[1:-1] == "amp":

               text = "&"

            elif text[1:-1] == "gt":

               text = ">"

            elif text[1:-1] == "lt":

               text = "<"

            else:

               print text[1:-1]

               text = unichr(htmlentitydefs.name2codepoint])

         except KeyError:

            print "keyerror"

            pass

      return text # leave as is

   return re.sub("&#?w+;", fixup, text)

希望能帮助到你。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值