【问题标题】:How to output Python3 (unicode) strings while ignoring un-encodable characters如何在忽略不可编码字符的同时输出 Python3(unicode)字符串
【发布时间】:2017-08-24 10:14:53
【问题描述】:

考虑以下终端命令行

python3 -c 'print("hören")'

在大多数终端中,这会打印“hören”(德语为“听到”),在 一些 终端中会出现错误

UnicodeEncodeError: 'ascii' codec can't encode character '\xf6' 
in position 1: ordinal not in range(128)

在我的 Python3 程序中,我不希望仅仅打印出一些 可以 引发这样的异常的内容,而是希望输出不会引发异常的字符。

所以我的问题是:如何在忽略不可编码字符的情况下输出 Python3(unicode)字符串?


一些注意事项

到目前为止我所做的尝试

  1. 我尝试使用sys.stdout.write而不是print,但仍然会出现编码问题。

  2. 我尝试通过 byes 对字符串进行编码

    bytes=line.encode('utf-8')
    

    这不会在打印时引发异常,但即使在有能力的终端中,非 ascii 字符也会被它们的代码点编号替换。

  3. 我尝试使用带有'ignore' 参数的decode 方法:

    bytes=line.encode('utf-8')
    decoded=bytes.decode('utf-8', 'ignore')
    print(decoded)
    

    但问题不在于字符串中的解码,而在于 in 中的 print 函数。

这里有些终端似乎不能支持所有字符

  • macOS 上 Emacs 中的 bash shell。

  • 通过do shell script 在 Applescript 中接收“打印”字符串,例如:

    set txt to do shell script "/usr/local/bin/python3 -c \"print('hören')\" "
    

更新:这些终端都从locale.getpreferredencoding()返回值US-ASCII

【问题讨论】:

    标签: python-3.x unicode character-encoding


    【解决方案1】:

    我的首选方法是根据您使用的终端设置PYTHONIOENCODING 变量。

    对于支持 UTF-8 的终端,您可以这样做:

    export PYTHONIOENCODING='utf-8'
    

    要在 ASCII 终端中打印 '?',您可以:

    export PYTHONIOENCODING='ascii:replace'
    

    或者更好的是,如果你不关心编码,你应该可以这样做:

    export PYTHONIOENCODING=':replace'
    

    【讨论】:

    • 很好的答案!我在设置export LANG=en_AU.UTF-8 方面取得了一些成功,但那是相当的武力;你的方法更有针对性。
    猜你喜欢
    • 2018-05-27
    • 2017-10-14
    • 2012-07-14
    • 2018-05-25
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 2011-08-13
    相关资源
    最近更新 更多