大5编码到utf-8转换不成功

1 投票
1 回答
4597 浏览
提问于 2025-04-18 00:05

我正在尝试做一些非常基础的字符集转换,类似于iconv的功能,但不知道为什么不成功。我在用Python的解码和编码功能,但感觉好像漏掉了什么很基本的东西。

代码:

#!/usr/bin/python

import sys

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print ("wrong input")
        sys.exit(1)

    fi = open(sys.argv[1], "r")
    buf = fi.read()
    fi.close()

    print ("got input: \n{0}".format(buf))

    buf.decode("big5", "strict").encode("utf8", "strict")

    fo = open(sys.argv[2], "w")
    fo.write(buf)
    fo.close()


    print ("changed: \n{0}".format(buf))

输入文件。hello.big5是通过用iconv将utf文件转换得到的。

[workspace] > cat hello.utf8 
hello = 你好

[workspace] > cat hello.big5 
hello = �A�n

执行时:

[workspace] > ./test.py  hello.big5 out
got input: 
hello = �A�n

changed: 
hello = �A�n

有人能告诉我哪里出错了吗?

1 个回答

1

这一行并没有像你想的那样修改 buf

buf.decode("big5", "strict").encode("utf8", "strict")

你可以在 encodedecode 的文档中看到。这些方法返回的是 字符串unicode 对象,而不会修改调用它们的对象。如果你想修改 buf,只需把结果赋值给它:

buf = buf.decode("big5", "strict").encode("utf8", "strict")

另外,如果你在用 Python2,使用 print 时加括号是没有意义的,这样会让人困惑。

撰写回答