我想解析我的XML文档。所以我将XML文档存储如下
class XMLdocs(db.Expando):
id = db.IntegerProperty()
name=db.StringProperty()
content=db.BlobProperty()
下面是我的代码
parser = make_parser()
curHandler = BasketBallHandler()
parser.setContentHandler(curHandler)
for q in XMLdocs.all():
parser.parse(StringIO.StringIO(q.content))
我正处于错误之下
'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 517, in __call__
handler.post(*groups)
File "/base/data/home/apps/parsepython/1.348669006354245654/mapreduce/base_handler.py", line 59, in post
self.handle()
File "/base/data/home/apps/parsepython/1.348669006354245654/mapreduce/handlers.py", line 168, in handle
scan_aborted = not self.process_entity(entity, ctx)
File "/base/data/home/apps/parsepython/1.348669006354245654/mapreduce/handlers.py", line 233, in process_entity
handler(entity)
File "/base/data/home/apps/parsepython/1.348669006354245654/parseXML.py", line 71, in process
parser.parse(StringIO.StringIO(q.content))
File "/base/python_runtime/python_dist/lib/python2.5/xml/sax/expatreader.py", line 107, in parse
xmlreader.IncrementalParser.parse(self, source)
File "/base/python_runtime/python_dist/lib/python2.5/xml/sax/xmlreader.py", line 123, in parse
self.feed(buffer)
File "/base/python_runtime/python_dist/lib/python2.5/xml/sax/expatreader.py", line 207, in feed
self._parser.Parse(data, isFinal)
File "/base/data/home/apps/parsepython/1.348669006354245654/parseXML.py", line 136, in characters
print ch
UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)
似乎您遇到了一个UTF-8字节顺序标记(BOM)。尝试使用此unicode字符串提取出物料清单:
我使用了
strip
而不是lstrip
,因为在您的例子中,您有多个BOM出现,可能是由于连接了文件内容。这个问题的实际最佳答案取决于您的环境,特别是您的终端期望的编码。
最快的单行解决方案是将您打印的所有内容编码为ASCII(您的终端几乎肯定会接受),同时丢弃无法打印的字符:
更好的解决方案是将终端的编码更改为utf-8,并在打印之前将所有内容编码为utf-8。每次打印或读取字符串时,您都应该养成考虑unicode编码的习惯。
只需将
.encode('utf-8')
放在对象的末尾就可以完成Python最新版本中的工作。相关问题 更多 >
编程相关推荐