Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python,将HTML实体转换为Unicode_Python_Unicode - Fatal编程技术网

Python,将HTML实体转换为Unicode

Python,将HTML实体转换为Unicode,python,unicode,Python,Unicode,(编辑:我正在使用Python 2.7) (编辑2:我已选中,解决方案无效。请不要将此标记为已回答。) 我一直找不到一个能够可靠地转换包含一些html实体的文本的python包。我发现HTMLPasser可以处理一些东西,但也会破坏很多东西。BeautifulSoup似乎从来都不适合转换为unicode。如何仅使用一种方法返回字符串a-d的unicode表示形式 我认为我遇到的问题是,我的一些文本同时包含unicode字符和html实体(如示例字符串d) 这将提供以下输出: a1: P&

(编辑:我正在使用Python 2.7) (编辑2:我已选中,解决方案无效。请不要将此标记为已回答。)

我一直找不到一个能够可靠地转换包含一些html实体的文本的python包。我发现HTMLPasser可以处理一些东西,但也会破坏很多东西。BeautifulSoup似乎从来都不适合转换为unicode。如何仅使用一种方法返回字符串a-d的unicode表示形式

我认为我遇到的问题是,我的一些文本同时包含unicode字符和html实体(如示例字符串d)

这将提供以下输出:

a1: P&O.
a2: P&O.
b1: & 
b2: & 
c1: >
c2: >
d1: > 150ÎC
d2: HTML Parse Broke!

编辑3:卡尔哈特的建议让我找到了一个解决方案。为了防止使用混合字符编码的字符串中断,我使用了.decode('utf-8')

如果需要unicode处理,请使用unicode字符串。那么,在您的示例中,一切都按预期进行

# -*- coding: utf-8 -*-
import HTMLParser
from bs4 import BeautifulSoup

astring = u"P&O."
bstring = u"& "
cstring = u">"
dstring = u"> 150ÎC"

pars = HTMLParser.HTMLParser()
a1 = BeautifulSoup('<span>%s</span>' % astring)
a2 = pars.unescape(astring)
print "a1:", a1
print "a2:", a2
b1 = BeautifulSoup('<span>%s</span>' % bstring)
b2 = pars.unescape(bstring)
print "b1:", b1
print "b2:", b2
c1 = BeautifulSoup('<span>%s</span>' % cstring)
c2 = pars.unescape(cstring)
print "c1:", c1
print "c2:", c2
d1 = BeautifulSoup('<span>%s</span>' % dstring)
try: d2 = pars.unescape(dstring)
except: d2 = "HTML Parse Broke!"
print "d1:", d1
print "d2:", d2
#-*-编码:utf-8-*-
导入HTMLPasser
从bs4导入BeautifulSoup
astring=u“P&O.”
bstring=u“&;”
cstring=u“”
dstring=u“150摄氏度”
pars=HTMLParser.HTMLParser()
a1=美化组(“%s”%astring)
a2=不可见部分(收敛)
打印“a1:”,a1
打印“a2:”,a2
b1=美化组(“%s”%b字符串)
b2=未景观部分(bstring)
打印“b1:”,b1
打印“b2:”,b2
c1=美化组(“%s”%cstring)
c2=未景观部分(cstring)
打印“c1:”,c1
打印“c2:”,c2
d1=美化组(“%s”%dstring)
try:d2=pars.unescape(dstring)
除了:d2=“HTML解析已中断!”
打印“d1:”,d1
打印“d2:”,d2
这将提供以下输出

a1: <span>P&amp;O.</span>
a2: P&O.
b1: <span>&amp; </span>
b2: & 
c1: <span>&gt;</span>
c2: >
d1: <span>&gt; 150ÎC</span>
d2: > 150ÎC
a1:P&;O。
a2:P&O。
b1:&;
b2:&
c1:
c2:>
d1:150摄氏度
d2:>150摄氏度

BeautifulSoup对它们进行编码,HTMLPasser对它们进行解码。

有吗?有。在本例中,我尝试使用unescape方法。在我引用的消息中有7个答案。你都试过了吗?;-)
a1: <span>P&amp;O.</span>
a2: P&O.
b1: <span>&amp; </span>
b2: & 
c1: <span>&gt;</span>
c2: >
d1: <span>&gt; 150ÎC</span>
d2: > 150ÎC