【问题标题】:Handling unicode in Python 2.7在 Python 2.7 中处理 unicode
【发布时间】:2013-09-23 00:03:40
【问题描述】:

我收到此错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2661' in position 1409: ordinal not in range(128)

我对编程还是很陌生,所以请怜悯我和我的无知。但我理解错误是它无法处理 unicode 字符。至少有一个 unicode 字符,但在该提要中可能还有无数其他字符。

我已经做了一些寻找有类似问题的其他人,但我找不到我理解或可以工作的解决方案。

#import library to do http requests:
import urllib
from xml.dom.minidom import parseString, parse

f = open('games.html', 'w')

document = urllib.urlopen('https://itunes.apple.com/us/rss/topfreemacapps/limit=300/genre=12006/xml')

dom = parse(document)

image = dom.getElementsByTagName('im:image')
title = dom.getElementsByTagName('title')
price = dom.getElementsByTagName('im:price')
address = dom.getElementsByTagName('id')

imglist = []
titlist = []
pricelist = []
addlist = []

i = 0
j = 20
k = 40

f.write('''\
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
<!--


A:link {text-decoration: none; color: #246DA8;}
A:visited {text-decoration: none; color: #246DA8;}
A:active {text-decoration: none; color: #40A9E3;}
A:hover {text-decoration: none; color: #40A9E3;}

.box {
    vertical-align:middle;
    width: 180px;
    height: 120px;
    border: 1px solid #99c;
    padding: 5px;
    margin: 0px;
    margin-left: auto;
    margin-right: auto;
    -moz-border-radius: 5px;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    background-color:#ffffff;
    font-family: Arial, Helvetica, sans-serif; color: black;
    font-size: small;
    font-weight: bold;
}


-->
</style>
</head>

<body>
''')

for i in range(0,len(image)):
    if image[i].getAttribute('height') == '53':
        imglist.append(image[i].firstChild.nodeValue)

for i in range(1,len(title)):
    titlist.append(title[i].firstChild.nodeValue)

for i in range(0,len(price)):
    pricelist.append(price[i].firstChild.nodeValue)

for i in range(1,len(address)):
    addlist.append(address[i].firstChild.nodeValue) 

for i in range(0,20):

            f.write('''
<div style="width: 600px;">
 <div style="float: left; width: 200px;">
    <div class="box" align="center">
        <div align="center">
            <a href="''' + addlist[i] + '''?at=10l5NR"  target="_blank">''' + titlist[i] + '''</a><br>
            <a href="''' + addlist[i] + '''?at=10l5NR" target="_blank"><img src="''' + imglist[i] + '''" alt="" width="53" height="53" border="0" ></a><br>
            <span>''' + pricelist[i] + '''</span>
        </div>
    </div>
 </div>
  <div style="float: left; width: 200px;">
 <div class="box" align="center">
        <div align="center">
            <a href="''' + addlist[i+j] + '''?at=10l5NR"  target="_blank">''' + titlist[i+j] + '''</a><br>
            <a href="''' + addlist[i+j] + '''?at=10l5NR" target="_blank"><img src="''' + imglist[i+j] + '''" alt="" width="53" height="53" border="0" ></a><br>
            <span>''' + pricelist[i+j] + '''</span>
        </div>
    </div>
 </div>
 <div style="float: left; width: 200px;">
 <div class="box" align="center">
        <div align="center">
            <a href="''' + addlist[i+k] + '''?at=10l5NR"  target="_blank">''' + titlist[i+k] + '''</a><br>
            <a href="''' + addlist[i+k] + '''?at=10l5NR" target="_blank"><img src="''' + imglist[i+k] + '''" alt="" width="53" height="53" border="0" ></a><br>
            <span>''' + pricelist[i+k] + '''</span>
        </div>
    </div>
</div>
<br style="clear: left;" />
</div>


<br>
''')
f.write('''</body>''')

f.close()

【问题讨论】:

  • 错误出现在哪一行?
  • Traceback(最近一次调用最后):文件“games.py”,第 114 行,在 ''') UnicodeEncodeError:'ascii' 编解码器无法编码字符 u'\u2661'在位置 1409:序数不在范围内(128)。但是脚本本身没有第 114 行,它正在对它接收的 xml 进行吐槽。
  • 如果脚本中没有第114行,这个“games.py”文件是什么,脚本是怎么调用的?
  • 顺便说一句,如果我运行你的这个脚本,它工作得非常好。你确定你做错了什么不在它之外吗?
  • 因为我是个白痴,并且引用了已编辑的行而不是原始行。对不起! f.write('''

标签: python xml python-2.7 unicode minidom


【解决方案1】:

基本问题是您将 Unicode 字符串与普通字节字符串连接起来,而没有使用适当的编码对其进行转换;在这些情况下,默认使用 ASCII(很明显,它不能处理扩展字符)。

脚本中执行此操作的行太长,无法引用,但另一个显示相同问题的实际示例可能如下所示:

parameter = u"foo \u2661"
sys.stdout.write(parameter + " bar\n")

您将需要使用明确指定的编码对 Unicode 字符串进行编码,例如像这样:

parameter = u"foo \u2661"
sys.stdout.write(parameter.encode("utf8") + " bar\n")

在您的情况下,您可以在循环中执行此操作,以便不必在每个串联中都指定它:

for i in range(1,len(title)):
    titlist.append(title[i].firstChild.nodeValue.encode("utf8"))

--

此外,虽然我们正在这样做,但您可以通过不使用整数索引迭代元素来改进您的代码。例如,而不是这个:

title = dom.getElementsByTagName('title')
for i in range(1,len(title)):
    titlist.append(title[i].firstChild.nodeValue.encode("utf8"))

...你可以这样做:

for title in dom.getElementsByTagName('title')
    titlist.append(title.firstChild.nodeValue.encode("utf8"))

【讨论】:

  • 你就是男人!感谢您的耐心和分享您的意见。有效!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-15
  • 2018-09-28
相关资源
最近更新 更多