在Python中解码HTML编码的字符串

1 投票
1 回答
1876 浏览
提问于 2025-04-15 11:51

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

"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脚本输出的一个例子...

骗局、恶作剧,还是实情,他âs 会努力揭开这个 骇人听闻的故事的真相, 希望在这个过程中能得到一个街机游戏。

1 个回答

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

这是输出结果:

不管是骗局、恶作剧,还是实事,他都会深入调查这个肮脏的故事,希望在这个过程中能得到一个街机游戏。

撰写回答