【问题标题】:Trouble converting a string from Unicode in Python 2.7?在 Python 2.7 中从 Unicode 转换字符串时遇到问题?
【发布时间】: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
  • 关于您的字典问题:Key1Key2Key3 真的是您的输出,还是您为这个问题手动编写的一些代码?因为它们是大写的,所以data['key1'] 不起作用。试试data['Key1'] ;-)

标签: python unicode beautifulsoup


【解决方案1】:

.string 值确实不是字符串。您需要将其转换为unicode()

name = unicode(i.find('a').string)

这是一个 unicode-like 对象,称为 NavigableString。如果您确实需要将其改为str,则可以从那里对其进行编码:

name = unicode(i.find('a').string).encode('utf8')

或类似的。对于在 dict 中使用,我会使用 unicode() 对象而不是编码。

要了解unicode()str() 之间的区别以及使用什么编码,我建议您阅读Python Unicode HOWTO

【讨论】:

    猜你喜欢
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-13
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多