如何在 Python 3.1 中对字符串中的 HTML 实体进行转义? [英] How do I unescape HTML entities in a string in Python 3.1?

查看:58
本文介绍了如何在 Python 3.1 中对字符串中的 HTML 实体进行转义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我环顾四周,只找到了适用于 python 2.6 及更早版本的解决方案,没有任何关于如何在 python 3.X 中执行此操作的信息.(我只能访问Win7 box.)

I have looked all around and only found solutions for python 2.6 and earlier, NOTHING on how to do this in python 3.X. (I only have access to Win7 box.)

我必须能够在 3.1 中做到这一点,最好在没有外部库的情况下做到这一点.目前,我已经安装了 httplib2 并可以访问命令提示符 curl(这就是我获取页面源代码的方式).不幸的是,curl 不会解码 html 实体,据我所知,我在文档中找不到解码它的命令.

I HAVE to be able to do this in 3.1 and preferably without external libraries. Currently, I have httplib2 installed and access to command-prompt curl (that's how I'm getting the source code for pages). Unfortunately, curl does not decode html entities, as far as I know, I couldn't find a command to decode it in the documentation.

是的,我曾尝试让 Beautiful Soup 发挥作用,但在 3.X 中很多次都没有成功.如果您能提供有关如何使其在 MS Windows 环境中在 python 3 中工作的明确说明,我将不胜感激.

YES, I've tried to get Beautiful Soup to work, MANY TIMES without success in 3.X. If you could provide EXPLICIT instructions on how to get it to work in python 3 in MS Windows environment, I would be very grateful.

所以,明确地说,我需要像这样转换字符串:Suzy &John 转换成这样的字符串:Suzy & John".

So, to be clear, I need to turn strings like this: Suzy & John into a string like this: "Suzy & John".

推荐答案

你可以使用 html.unescape:

Python3.4+ 中(感谢 J.F. Sebastian 的更新):

In Python3.4+ (thanks to J.F. Sebastian for the update):

import html
html.unescape('Suzy & John')
# 'Suzy & John'

html.unescape('"')
# '"'

Python3.3 或更早版本中:

import html.parser    
html.parser.HTMLParser().unescape('Suzy & John')

Python2 中:

import HTMLParser
HTMLParser.HTMLParser().unescape('Suzy & John')

这篇关于如何在 Python 3.1 中对字符串中的 HTML 实体进行转义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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