2012-03-12 78 views
1

我正在寻找或者忽略我的xml中的unicode。我愿意以某种方式在输出处理中改变它。用python和lxml忽略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-','')加回我得到这个错误都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,这样我就可以输出targetoutFile.write

+1

当你从__future__导入unicode_literals时会发生什么? – 2012-03-12 21:20:38

回答

4

你会得到这个错误,因为你有一个带有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")) 
+0

是的 - 当我刚刚将'.encode(“UTF-8”)'添加到'print'和'write'输出代码时,这工作。非常感谢! – 2012-03-12 21:52:40

0

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字符。