Python将html ascii编码的文本转换为utf8 [英] Python convert html ascii encoded text to utf8

查看:317
本文介绍了Python将html ascii编码的文本转换为utf8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个xml文件,我需要转换为utf8。
不幸的是,实体包含这样的文本:

 / mytext, 

我正在使用编解码器库将文件转换为utf8,但html实体将无法使用



有没有一个简单的方法来摆脱html编码?



谢谢

解决方案

您可以通过 unescape 函数,然后将其传递给XML解析器。



或者,如果您只解析HTML , lxml的http解析器为您做到这一点:

 >>> import lxml.html 
>>> html = lxml.html.fromstring(< html>< body>< p>&#047; mytext&#044;< / p>< / body>< / html>)
>>>> lxml.html.tostring(html)
'< html>< body>< p> / mytext< / p>< / body>< / html>'


I have a xml file, which I need to convert to utf8. Unfortunately the entities contain text like this:

&#047;mytext&#044;

I'm using the codec library to convert files to utf8, but html entities won't work with it.

Is there an easy way to get rid of the html encoding?

Thanks

解决方案

You can pass the text of the file through an unescape function before passing it to the XML parser.

Alternatively, if you're only parsing HTML, lxml's http parser does this for you:

>>> import lxml.html
>>> html = lxml.html.fromstring("<html><body><p>&#047;mytext&#044;</p></body></html>")
>>> lxml.html.tostring(html)
'<html><body><p>/mytext,</p></body></html>'

这篇关于Python将html ascii编码的文本转换为utf8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆