使用python和lxml忽略xml中的unicode?

Hol*_*Sir 1 python xml unicode lxml python-unicode

我想忽略我的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")
Run Code Online (Sandbox Code Playgroud)

创建以下内容的输出:

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
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试重新添加,则'-'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)
Run Code Online (Sandbox Code Playgroud)

如何忽略unicode,以便可以target使用outFile.write

Epc*_*lon 5

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

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

我建议阅读Joels ,绝对绝对是每个软件开发人员的绝对最低知识,肯定要了解Unicode和字符集(无借口!),然后阅读Python文档中有关编码和解码字符串的相关章节。

这是一个入门的小提示:

print "docID:    {0}\nCitation: {1}\n".format(docID.encode("UTF-8"),
                                              target.encode("UTF-8"))
Run Code Online (Sandbox Code Playgroud)