【问题标题】:How can I change this function to be compatible with Python 2 and Python 3? I'm running into string, unicode and other problems如何更改此函数以与 Python 2 和 Python 3 兼容?我遇到了字符串、unicode 和其他问题
【发布时间】:2017-10-05 19:31:31
【问题描述】:

我有一个功能,旨在使文件名或 URL 的某些文本安全。我正在尝试对其进行更改,以便它在 Python 2 和 Python 3 中工作。在我的尝试中,我将自己与字节码混淆了,并欢迎一些指导。我遇到了像sequence item 1: expected a bytes-like object, str found 这样的错误。

def slugify(
    text       = None,
    filename   = True,
    URL        = False,
    return_str = True
    ):

    if sys.version_info >= (3, 0):

        # insert magic here

    else:

        if type(text) is not unicode:
            text = unicode(text, "utf-8")
        if filename and not URL:
            text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore")
            text = unicode(re.sub("[^\w\s-]", "", text).strip())
            text = unicode(re.sub("[\s]+", "_", text))
        elif URL:
            text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore")
            text = unicode(re.sub("[^\w\s-]", "", text).strip().lower())
            text = unicode(re.sub("[-\s]+", "-", text))
        if return_str:
            text = str(text)

    return text

【问题讨论】:

    标签: regex string python-3.x unicode bytecode


    【解决方案1】:

    当您不确定原始类型是什么时,您的主要问题似乎是弄清楚如何将文本转换为 unicode 并返回字节。事实上,如果你小心的话,你可以在没有任何条件检查的情况下做到这一点。

    if isinstance(s, bytes):
        s = s.decode('utf8')
    

    应该足以在 Python 2 或 3 中将某些内容转换为 unicode(通常假设为 2.6+ 和 3.2+)。这是因为 bytes 在 Python 2 中作为字符串的别名存在。显式的 utf8 参数仅在 Python 2 中是必需的,但在 Python 3 中提供它也没有什么坏处。然后要转换回字节串,你只需做相反的事情。

    if not isinstance(s, bytes):
        s = s.encode('utf8')
    

    当然,我建议您认真考虑一下为什么您不确定您的字符串首先具有哪些类型。最好将区别分开,而不是编写接受任何一个的“弱” API。 Python 3 只是鼓励你保持分离。

    【讨论】:

    • not isinstance(s, bytes) 将始终为真。您的意思是在第一个 sn-p 中将 s.decode('utf-8') 分配给 s 以外的其他东西吗?
    • @jwodder 的想法是在 sn-ps 之间会有其他代码。如果您不知道现有类型,我只是展示了如何将某些内容转换为 unicode 或字节。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    相关资源
    最近更新 更多