gpt4 book ai didi

python - 在 iso8859_1 和 utf-8 之间转换 Python 字符串

转载 作者:太空宇宙 更新时间:2023-11-03 15:55:02 26 4
gpt4 key购买 nike

我正在尝试在 python 中做与下面的 java 代码相同的事情。

String decoded = new String("中".getBytes("ISO8859_1"), "UTF-8");
System.out.println(decoded);

输出是一个中文字符串“中”。

在Python中,我尝试了编码/解码/字节数组,但总是得到不可读的字符串。我认为我的问题是我不太了解java/python编码机制是如何工作的。我也无法从现有答案中找到解决方案。

#coding=utf-8

def p(s):
print s + ' -- ' + str(type(s))

ch1 = 'ä¸-'
p(ch1)

chu1 = ch1.decode('ISO8859_1')
p(chu1.encode('utf-8'))

utf_8 = bytearray(chu1, 'utf-8')
p(utf_8)

p(utf_8.decode('utf-8').encode('utf-8'))

#utfstr = utf_8.decode('utf-8').decode('utf-8')
#p(utfstr)

p(ch1.decode('iso-8859-1').encode('utf8'))
ä¸- --  <type 'str'>
ä¸Â- -- <type 'str'>
ä¸Â- -- <type 'bytearray'>
ä¸Â- -- <type 'str'>
ä¸Â- -- <type 'str'>

Daniel Roseman 的回答非常接近。谢谢。但当谈到我的真实案例时:

    ch = 'masanori harigae ã\201®ã\203\221ã\203¼ã\202½ã\203\212ã\203«ä¼\232è-°å®¤'
print ch.decode('utf-8').encode('iso-8859-1')

我得到

回溯(最近一次调用最后一次): 文件“”,第 1 行,位于 文件“/apps/Python/lib/python2.7/encodings/utf_8.py”,第 16 行,解码 返回codecs.utf_8_decode(输入,错误,True)UnicodeDecodeError:“utf8”编解码器无法解码位置 19 中的字节 0x81:无效起始字节

Java代码:

    String decoded = new String("masanori harigae ã\201®ã\203\221ã\203¼ã\202½ã\203\212ã\203«ä¼\232è-°å®¤".getBytes("ISO8859_1"), "UTF-8");
System.out.println(decoded);

输出为 Masanori harigae のパーソナル会�-�室

最佳答案

你的做法是错误的。您有一个错误编码为 utf-8 的字节串,并且您希望将其解释为 iso-8859-1:

>>> ch = "中"
>>> print u.decode('utf-8').encode('iso-8859-1')

关于python - 在 iso8859_1 和 utf-8 之间转换 Python 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40889917/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com