从big5到utf8的解码/编码不起作用

2024-10-06 12:47:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试像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))

输入文件。你好。大5通过使用iconv转换utf文件获得

^{pr2}$

执行时:

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

changed: 
hello = �A�n

有人能指出我在哪里绊倒吗?在


Tags: formathellocloseinputifsysopenfi
1条回答
网友
1楼 · 发布于 2024-10-06 12:47:54

这一行没有修改buf,因为您似乎在想:

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

您可以在文档中看到^{}^{}。这些方法返回字符串unicode对象,它们不修改调用对象的。如果要修改buf,只需为其指定结果:

^{pr2}$

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

相关问题 更多 >