如何更正存储为ASCII的UTF8字符

2024-09-30 04:33:31 发布

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

我有一些以ASCII格式存储的旧数据。很明显,UTF-8数据在被写入之前没有正确地转换成ASCII。例如,José将在文件中显示为José。我可以用下面的Java代码片段轻松解决这个问题:

byte[] utf8Bytes = c_TOBETRANSLATED.getBytes("ISO-8859-1");
String s2 = new String(utf8Bytes,"UTF-8");

但是我需要用我剩下的代码来完成这个Python。我只是刚刚开始使用Python,我的互联网搜索和试错并不能帮助我找到一个Python解决方案来做同样的事情。你知道吗


Tags: 文件数据代码string格式asciiisojava
2条回答

如果文件中有"José",则文件查看器读取/显示的数据不正确。它是UTF-8,但是用错误的编码解码。示例:

import locale

# Correctly written
with open('file.txt','w',encoding='utf8') as f:
    f.write('José')

# The default encoding for open()
print(locale.getpreferredencoding(False))

# Incorrectly opened
with open('file.txt') as f:
    data = f.read()
    print(data)
    # What I think you are requesting as a fix.
    # Re-encode with the incorrect encoding, then decode correctly.
    print(data.encode('cp1252').decode('utf8'))

# Correctly opened
with open('file.txt',encoding='utf8') as f:
    print(f.read())

输出:

cp1252
José
José
José

如果您使用的是Python 3,那么可以使用bytes function执行以下操作:

test = "José"
fixed = bytes(test, 'iso-8859-1').decode('utf-8')
# fixed will now contain the string José

相关问题 更多 >

    热门问题