首页 文章

Python将字符串保存到文件 . Unicode错误

提问于
浏览
2

我正在使用Python中的Spreadsheet API从Google电子表格中提取数据 . 我可以使用for循环在命令行上打印电子表格的每一行,但是一些文本包含符号,例如摄氏度符号(小圆圈) . 当我在命令行上打印这些行时,我想将它们写入文件 . 但是当我这样做时,我得到了不同的unicode错误 . 我尝试手动解决它,但有太多:

current=current.replace(u'\xa0',u'')
current=current.replace(u'\u000a',u'p')
current=current.replace(u'\u201c',u'\"')
current=current.replace(u'\u201d',u'\"')
current=current.replace(u'\u2014',u'-')

我该怎么办才能得到错误?例如

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

current=current.replace(u'\u0446',u'u')

3 回答

  • 0

    您想要从它所处的编码中解码它:

    decoded_str = encoded_str.decode('utf-8')
    

    有关如何处理unicode字符串的更多信息,你应该仔细阅读http://docs.python.org/howto/unicode.html

  • 5
    import unicodedata
    decoded = unicodedata.normalize('NFKD', encoded).decode('UTF-8', 'ignore')
    

    我不太确定在这种情况下需要规范化 . 此外,忽略选项意味着您可能会丢失一些信息,因为将忽略解码错误 .

  • -1
    ''.join(c for c in current if ord(c) < 128)
    

相关问题