我希望忽略我的 xml 中的 unicode。我也愿意在输出处理中以某种方式改变它。
我的 python :
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-','') 中添加回来print 我都收到了这个错误和 outFile.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 ?
请您参考如下方法:
您收到此错误是因为您有一个包含 unicode 字符的字符串,您正尝试使用 ascii 字符集输出该字符串。打印列表时,您将获得列表的“repr”及其中的字符串,从而避免了该问题。
您需要编码为不同的字符集(例如 UTF-8),或者在编码时去除或替换无效字符。
我推荐阅读 Joels The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) ,后面是the Python docs中关于字符串编码和解码的相关章节.
这里有一个小提示可以帮助您入门:
print "docID: {0}\nCitation: {1}\n".format(docID.encode("UTF-8"),
target.encode("UTF-8"))
