Python2.7学习笔记-中文编码通用转码函数

Python2.7 中文编码通用转码函数

  • Python2.7学习笔记-中文编码通用转码函数

Python2.7学习笔记-中文编码通用转码函数

# encoding handler begin
def getCoding(strInput):
    """
    获取编码格式
    """
    if isinstance(strInput, unicode):
        return "unicode"
    try:
        strInput.decode("utf8")
        return 'utf8'
    except:
        pass

    try:
        strInput.decode("gbk")
        return 'gbk'
    except:
        pass

    try:
        strInput.decode("ascii")
        return 'ascii'
    except:
        pass

    return False


def tran2Unicode(strInput):
    """
    转化为utf8格式
    """
    strCodingFmt = getCoding(strInput)
    if strCodingFmt == "utf8":
        return strInput.decode("utf8")
    elif strCodingFmt == "unicode":
        return strInput
    elif strCodingFmt == "gbk":
        return strInput.decode("gbk")
    elif strCodingFmt == 'ascii':
        return unicode(strInput)
    return ''


def tran2UTF8(strInput):
    """
    转化为utf8格式
    """
    strCodingFmt = getCoding(strInput)
    if strCodingFmt == "utf8":
        return strInput
    elif strCodingFmt == "unicode":
        return strInput.encode("utf8")
    elif strCodingFmt == "gbk":
        return strInput.decode("gbk").encode("utf8")
    elif strCodingFmt == "ascii":
        return strInput.encode("utf8")
    return ''


def tran2GBK(strInput):
    """
    转化为gbk格式
    """
    strCodingFmt = getCoding(strInput)
    if strCodingFmt == "gbk":
        return strInput
    elif strCodingFmt == "unicode":
        return strInput.encode("gbk")
    elif strCodingFmt == "utf8":
        return strInput.decode("utf8").encode("gbk")
    elif strCodingFmt == "ascii":
        return strInput.encode("utf8")
    return ''
# encoding handler end

你可能感兴趣的:(python,python)