【问题标题】:Ignore unicode in xml with python and lxml?使用python和lxml忽略xml中的unicode?
【发布时间】:2012-03-29 07:34:09
【问题描述】:

我希望忽略我的 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,以便可以将 targetoutFile.write 串起来?

【问题讨论】:

  • 当你from __future__ import unicode_literals时会发生什么?

标签: python xml unicode lxml python-unicode


【解决方案1】:

您收到此错误是因为您尝试使用 ascii 字符集输出包含 unicode 字符的字符串。打印列表时,您将获得列表的“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"))

【讨论】:

  • 是的 - 当我刚刚将 .encode("UTF-8") 添加到 printwrite 输出代码时,这有效。非常感谢!
【解决方案2】:

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) &lt; 128 else '.' for a in x])

这会将所有非 ASCII 字符替换为 '.'。

【讨论】:

    猜你喜欢
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    相关资源
    最近更新 更多