【发布时间】:2012-12-20 21:40:03
【问题描述】:
我对 Python 2.x 中的 unicode 感到非常困惑。
我正在使用 BeautifulSoup 抓取网页,并尝试将我找到的内容插入到字典中,名称为键,url 为值。
我正在使用 BeautifulSoup 的 find 函数来获取我需要的信息。我的代码开始如下:
name = i.find('a').string
url = i.find('a').get('href')
这可行,除了从find 返回的thign 是一个对象,而不是一个字符串。
有些事情让我感到困惑
如果我在将其分配给变量之前尝试将其转换为类型str,它有时会抛出UnicodeEncodeError。
'ascii' codec can't encode character u'\xa0' in position 5: ordinal not in range(128)
我搜索了一下,发现我应该编码为ascii
我尝试添加:
print str(i.find('a').string).encode('ascii', 'ignore')
不走运,仍然给出一个 Unicode 错误。
从那里,我尝试使用repr。
print repr(i.find('a').string)
这行得通……几乎!
我在这里遇到了一个新问题。
一旦一切都说完了,字典也建好了,我就不能访问任何东西了!它一直给我一个KeyError。
我可以遍历字典:
for i in sorted(data.iterkeys()):
print i
>>> u'Key1'
>>> u'Key2'
>>> u'Key3'
>>> u'Key4'
但是如果我尝试像这样访问字典的一个项目:
print data['key1']
或
print data[u'key1']
或
test = unicode('key1')
print data[test]
它们都返回 KeyErrors,这让我 100% 感到困惑。我认为这与它们是 Unicode 对象有关。
我几乎尝试了所有我能想到的方法,但我不知道发生了什么。
哦!更奇怪的是,这段代码:
name = repr(i.find('a').string)
print type(name)
返回
>>> type(str)
但如果我只是打印这个东西
print name
它显示为一个 unicode 字符串
>>>> u'string name'
【问题讨论】:
-
这超出了 BeautifulSoup 的范围,请务必阅读(为方便起见,不要跳过部分内容):docs.python.org/2/howto/unicode.html
-
关于您的字典问题:
Key1、Key2和Key3真的是您的输出,还是您为这个问题手动编写的一些代码?因为它们是大写的,所以data['key1']不起作用。试试data['Key1'];-)
标签: python unicode beautifulsoup