在没有 six.text_type 的情况下编写 py2.x 和 py3.x 兼容代码

Writing py2.x and py3.x compatible code without six.text_type

给定 six.text_type 函数。为 unicode 文本编写 i/o 代码很容易,例如https://github.com/nltk/nltk/blob/develop/nltk/parse/malt.py#L188

fout.write(text_type(line))

但是如果没有 six 模块,它需要一个 try-except 体操,如下所示:

try:
    fout.write(text_type(line))
except:
    try:
        fout.write(unicode(line))
    except:
        fout.write(bytes(line))

解决文件写入 unicode 行并确保 python 脚本与 py2.x 和 py3.x 兼容的 pythonic 方法是什么?

pythonic 上面的try-except 是处理py2to3 兼容性的方法吗?还有哪些其他选择?


更多 details/context 这个问题:https://github.com/nltk/nltk/issues/1080#issuecomment-134542174

six 做的事,并定义 text_type 自己:

try:
    # Python 2
    text_type = unicode
except NameError:
    # Python 3
    text_type = str

在任何情况下,从不 在此处使用空白的 except 行,您将掩盖与使用不同 Python 版本完全无关的其他问题。

不过,我不清楚您要写入的是哪种文件对象。如果您使用 io.open() 打开文件,您将获得一个文件对象,该对象始终需要 Unicode 文本,在 Python 2 和 3 中,您不需要将文本转换为 bytes, 永远.