UnicodeEncodeError: 'ascii' 编解码器无法对位置 0 处的字符 u'\xef' 进行编码:序数不在范围内 (128)

2023-12-01

我想解析我的 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)   

此问题的实际最佳答案取决于您的环境,特别是您的终端期望的编码。

最快的一行解决方案是将您打印的所有内容编码为 ASCII,您的终端几乎肯定会接受它,同时丢弃您无法打印的字符:

print ch #fails
print ch.encode('ascii', 'ignore')

更好的解决方案是将终端的编码更改为 utf-8,并在打印之前将所有内容编码为 utf-8。您应该养成每次打印或读取字符串时考虑 unicode 编码的习惯。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

UnicodeEncodeError: 'ascii' 编解码器无法对位置 0 处的字符 u'\xef' 进行编码:序数不在范围内 (128) 的相关文章

随机推荐