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)

ユニコードを無視し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!)を読むことをお勧めます.

開始するための小さなヒントを次に示します。

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文字セットに含まれていないすべての文字は16進エスケープシーケンスとして表示されます。たとえば、「\u201c」は「\xe2 \ x80\x9c」として表示されます。これが受け入れられない場合は、次のことができます。

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

これにより、すべての非ASCII文字が「。」に置き換えられます。

于 2012-03-12T21:39:31.553 に答える