首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python 3中的字符编码转换

python 3中的字符编码转换
EN

Stack Overflow用户
提问于 2013-01-13 03:40:05
回答 2查看 5.2K关注 0票数 3

在python 2.x中,我使用了

代码语言:javascript
复制
"shift-jis".decode('shift-jis').encode('utf-8')

但是在Python3.x中没有更多的str.decode()。在python 3.x中对应的代码是什么?

更新:

更具体:

python2函数是

代码语言:javascript
复制
def unzip(file, dir):
    zips = zipfile.ZipFile(file)
    for info in zips.infolist():
        info.filename = info.filename.decode('shift-jis').encode('utf-8')
        zips.extract(info,dir)

        print(info, filename)

此函数的等效python3代码是什么?

EN

回答 2

Stack Overflow用户

发布于 2013-01-13 04:18:10

关于您更新的问题:

代码语言:javascript
复制
def unzip(file, directory): # dir is a keyword
    with zipfile.ZipFile(file, mode='r') as zips:
        zips.printdir()
        zips.extractall(directory)

代码语言:javascript
复制
>>> b'\x82\xb3'.decode('shiftjis')
'さ'
>>> b'\x82\xb3'.decode('shift-jis')
'さ'
>>> b'\x82\xb3'.decode('shift_jis')
'さ'
>>> '日本語'.encode('shiftjis')
b'\x93\xfa\x96{\x8c\xea'
>>> b'\x93\xfa\x96{\x8c\xea'.decode('shiftjis')
'日本語'

在读取文件时:

代码语言:javascript
复制
with open('shiftjis.txt', 'r', encoding='shiftjis') as file:
    # do something with it

阅读更多:http://docs.python.org/3.3/library/io.html#i-o-base-classes

一个不太明智的版本:

代码语言:javascript
复制
with open('shiftjis.txt', 'rb') as file:
    string = file.read().decode('shift-jis')
票数 5
EN

Stack Overflow用户

发布于 2014-01-24 12:21:17

我需要自己来做这件事,最天真的做法是:

代码语言:javascript
复制
def unzip(file, dir):
    zips = zipfile.ZipFile(file)
    for info in zips.infolist():
        info.filename = info.filename.encode("cp437").decode("shift-jis")
    print("Extracting: " + info.filename.encode(sys.stdout.encoding,errors='replace').decode(sys.stdout.encoding))
    zips.extract(info,dir)
    print("")

ZipFile似乎在内部将所有文件名都视为DOS (代码页437)。与Python2不同,Python3在内部将所有字符串存储为某种UTF。因此,我们将文件名转换为字节数组,并将原始字节串解码为shift-JIS以得到最终的文件名。

print代码行执行类似的操作,但使用的是stdout和back的默认编码。这可以防止在Windows上发生错误,因为它的终端几乎从不支持Unicode。(如果是,则应正确显示名称。)

这对于几个zip文件来说工作得很好,直到...

代码语言:javascript
复制
Traceback (most recent call last):
  File "jp\j-unzip.py", line 73, in <module>
    unzip(archname,archpath)
  File "jp\j-unzip.py", line 68, in unzip
    info.filename = info.filename.encode("cp437").decode("shift-jis")
UnicodeDecodeError: 'shift_jis' codec can't decode byte 0x8f in position 28: illegal multibyte sequence

奖励内容!这个问题让人费解,但问题是一些有效的shift-JIS字符包含反斜杠,ZipFile会将其转换为正斜杠!例如,在shift-JIS中将十编码为8F 5C。这将被转换为非法序列的8F 2F。如果出现错误,下面(可能过于复杂)的代码会检查这种情况,并试图修复它。但可能还有其他字符会发生这种情况,并且序列是有效的,因此您会得到错误的字符,而不是错误。:(

代码语言:javascript
复制
def convert_filename(inname):
    err_ctr=0
    keep_going = True

    trans_filename = bytearray(inname.encode("cp437"))

    while keep_going:
        keep_going = False

        try:
            outname = trans_filename.decode("shift-jis")
        except UnicodeDecodeError as e:
            keep_going = True

            if e.args[4]=="illegal multibyte sequence":
                p0, p1 = e.args[2], e.args[3]
                print("Trying to fix encoding error at positions " + str(p0) +", "+ str(p1) + " caused by shift-jis sequence " + hex(trans_filename[p0]) +", "+  hex(trans_filename[p1]) )

                if (trans_filename[p0]>127 and trans_filename[p1] == 0x2f):
                    trans_filename[p1] = 0x5c
                else:
                    print("Don't know how to fix this error. Quitting. :(")
                    raise e

                err_ctr = err_ctr + 1
                print("This is error #" + str(err_ctr) + " for this filename.")
            else:
                raise e

        if err_ctr>50:
            print("More than 50 iterations. Are we stuck in an endless loop? Quitting...")
            sys.exit(1)

    return outname

def unzip(file, dir):
    zips = zipfile.ZipFile(file)
    for info in zips.infolist():
        info.filename = convert_filename(info.filename)
    print("Extracting: " + info.filename.encode(sys.stdout.encoding,errors='replace').decode(sys.stdout.encoding))
    zips.extract(info,dir)
    print("")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14297204

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档