【问题标题】:Writing py2.x and py3.x compatible code without six.text_type编写 py2.x 和 py3.x 兼容的代码,无需使用 Six.text_type
【发布时间】:2015-08-25 10:20:30
【问题描述】:

给定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 方法是什么?

上面的try-except是处理py2to3兼容性的pythonic方式吗?还有什么其他选择?


有关此问题的更多详细信息/上下文:https://github.com/nltk/nltk/issues/1080#issuecomment-134542174

【问题讨论】:

    标签: python-2.7 python-3.x unicode io six


    【解决方案1】:

    six 所做的事情,并自己定义text_type

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

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

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

    【讨论】:

    • 巧妙修复!!!注意到bytes 转换,我将检查字节的使用方式/原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    • 2013-10-25
    • 2012-07-20
    • 1970-01-01
    相关资源
    最近更新 更多