1

我希望忽略我的 xml 中的 unicode。我愿意在处理输出时以某种方式改变它。

我的蟒蛇:

import urllib2, os, zipfile 
from lxml import etree

doc = etree.XML(item)
docID = "-".join(doc.xpath('//publication-reference/document-id/*/text()'))
target = doc.xpath('//references-cited/citation/nplcit/*/text()')
#target = '-'.join(target).replace('\n-','')
print "docID:    {0}\nCitation: {1}\n".format(docID,target) 
outFile.write(str(docID) +"|"+ str(target) +"\n")

创建以下输出:

docID:    US-D0607176-S1-20100105
Citation: [u"\u201cThe birth of Lee Min Ho's donuts.\u201d Feb. 25, 2009. Jazzholic. Apr. 22, 2009 <http://www

但是,如果我尝试重新添加,'-'join(target).replace('\n-','')我会同时得到这个错误printoutFile.write

Traceback (most recent call last):
  File "C:\Documents and Settings\mine\Desktop\test_lxml.py", line 77, in <module>
    print "docID:    {0}\nCitation: {1}\n".format(docID,target)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 0: ordinal not in range(128)

我怎样才能忽略 unicode,以便我可以target使用outFile.write?

4

2 回答 2

5

您收到此错误是因为您尝试使用 ascii 字符集输出包含 unicode 字符的字符串。打印列表时,您将获得列表的“repr”以及其中的字符串,从而避免了该问题。

您需要编码为不同的字符集(例如 UTF-8),或者在编码时去除或替换无效字符。

我建议阅读 Joels The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) ,然后是 Python 文档中有关编码和解码字符串的相关章节。

这里有一个小提示可以帮助您入门:

print "docID:    {0}\nCitation: {1}\n".format(docID.encode("UTF-8"),
                                              target.encode("UTF-8"))
于 2012-03-12T21:38:42.463 回答
1

print "docID: {0}\nCitation: {1}\n".format(docID.encode("utf-8"), target.encode("utf-8"))

所有不在 ASCII 字符集中的字符都将显示为十六进制转义序列:例如“\u201c”将显示为“\xe2\x80\x9c”。如果这是不可接受的,那么您可以这样做:

docID = "".join([a if ord(a) < 128 else '.' for a in x])

它将用“。”替换所有非 ASCII 字符。

于 2012-03-12T21:39:31.553 回答