我有一些 CSV 文件需要从 shift-jis 转换为 utf-8。
这是我用 PHP 编写的代码,它成功转码为可读文本。
$str = utf8_decode($str);
$str = iconv('shift-jis', 'utf-8'. '//TRANSLIT', $str);
echo $str;
Run Code Online (Sandbox Code Playgroud)
我的问题是如何在 Python 中做同样的事情。
我不懂 PHP,但是这行得通吗:
mystring.decode('shift-jis').encode('utf-8') ?
Run Code Online (Sandbox Code Playgroud)
我还假设 CSV 内容来自文件。在 python 中打开文件有几个选项。
with open(myfile, 'rb') as fin
Run Code Online (Sandbox Code Playgroud)
将是第一个,您将获得原样的数据
with open(myfile, 'r') as fin
Run Code Online (Sandbox Code Playgroud)
将是默认文件打开
此外,我尝试使用 shift-js 文本计算我的计算机,并且以下代码有效:
with open("shift.txt" , "rb") as fin :
text = fin.read()
text.decode('shift-jis').encode('utf-8')
Run Code Online (Sandbox Code Playgroud)
结果在 UTF-8 中如下(没有任何错误)
' \xe3\x81\xa6 \xe3\x81\xa7 \xe3\x81\xa8'
Run Code Online (Sandbox Code Playgroud)
好的,我验证了我的解决方案:)
第一个字符确实是好字符: "\xe3\x81\xa6" 表示 "E3 81 A6" 它给出了正确的结果。
你可以试试这个网址