在python中解码html编码的字符串

时间:2009-05-27 04:32:51

标签: python html xml

我有以下字符串......

"Scam, hoax, or the real deal, he’s gonna work his way to the bottom of the sordid tale, and hopefully end up with an arcade game in the process."

我需要把它变成这个字符串......

  

骗局,骗局或真实交易,   他会按照他的方式工作   肮脏的故事的底部,和   希望最终得到一个街机游戏   在这个过程中。

这是非常标准的HTML编码,我不能为我的生活弄清楚如何在python中转换它。

我发现了这个: GitHub

它非常接近工作,但它不会输出撇号,而是输出一些unicode字符。

以下是GitHub脚本输出的示例...

  

骗局,恶作剧或真正的交易,他   要努力工作到底部   肮脏的故事,希望最终结束   在这个过程中使用街机游戏。

1 个答案:

答案 0 :(得分:4)

你正在尝试做什么被称为“HTML实体解码”,它包含在许多过去的Stack Overflow问题中,例如:

以下是使用Beautiful Soup HTML解析库对您的示例进行解码的代码段:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from BeautifulSoup import BeautifulSoup

string = "Scam, hoax, or the real deal, he’s gonna work his way to the bottom of the sordid tale, and hopefully end up with an arcade game in the process."
s = BeautifulSoup(string,convertEntities=BeautifulSoup.HTML_ENTITIES).contents[0]
print s

这是输出:

  

骗局,恶作剧或真正的交易,他是   要努力工作到底部   肮脏的故事,希望最终结束   在这个过程中使用街机游戏。