gpt4 book ai didi

python - UnicodeEncodeError : 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128)

转载 作者:IT老高 更新时间:2023-10-28 21:33:41 24 4
gpt4 key购买 nike

我想解析我的 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 编码的习惯。

关于python - UnicodeEncodeError : 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5141559/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com