我有一个数据源,这是我无法控制的,它用不同的编码发送字符串,而且我无法预先知道编码!我需要知道格式,才能正确地解码和存储我理解和控制的格式,比如UTF-8。
例如:
应改为
我尝试过的:
> stringToTest="J'ai déjÃ\xa0 un problème, après... je ne sais pas"
# there is no decode for string, directly, but one can try
> stringToTest.encode().decode()
"J'ai déjÃ\xa0 un problème, après... je ne sais pas"
# what does not help :)经过反复试验,我发现编码是iso-8859-1。
> stringToTest.encode('iso-8859-1').decode()
"J'ai déjà un problème, après... je ne sais pas"我想要/需要的是自动找到'iso-8859-1‘!
我试着用chardet!
> import chardet
> chardet.detect(stringToTest)
Traceback (most recent call last):
File "/snap/pycharm-community/188/plugins/python-ce/helpers/pydev/_pydevd_bundle/pydevd_exec2.py", line 3, in Exec
exec(exp, global_vars, local_vars)
File "<input>", line 1, in <module>
File "/usr/lib/python3/dist-packages/chardet/__init__.py", line 34, in detect
'{0}'.format(type(byte_str)))
TypeError: Expected object of type bytes or bytearray, got: <class 'str'>但是..。因为它是一根绳子..。chardet不接受!而且,我很惭愧地承认,但我没有设法将字符串转换成chardet接受的东西!
> test1=b"J'ai déjà un problème, après... je ne sais pas"
File "<input>", line 1
SyntaxError: bytes can only contain ASCII literal characters.
# Ok str and unicode are similar things... but who knows?!?!
> test1=u"J'ai déjà un problème, après... je ne sais pas"
> chardet.detect(test1)
Traceback (most recent call last):
File "/snap/pycharm-community/188/plugins/python-ce/helpers/pydev/_pydevd_bundle/pydevd_exec2.py", line 3, in Exec
exec(exp, global_vars, local_vars)
File "<input>", line 1, in <module>
File "/usr/lib/python3/dist-packages/chardet/__init__.py", line 34, in detect
'{0}'.format(type(byte_str)))
TypeError: Expected object of type bytes or bytearray, got: <class 'str'>
# NOP
> bytes(stringToTest)
Traceback (most recent call last):
File "/snap/pycharm-community/188/plugins/python-ce/helpers/pydev/_pydevd_bundle/pydevd_exec2.py", line 3, in Exec
exec(exp, global_vars, local_vars)
File "<input>", line 1, in <module>
TypeError: string argument without an encoding为什么不统一?!?
from unidecode import unidecode
from unidecode import unidecode
unidecode(stringToTest)
'J\'ai dA(c)jA un problA"me, aprA"s... je ne sais pas'发布于 2020-04-10 08:11:21
弦
"J'ai déjÃ\xa0 un problème, après... je ne sais pas"是莫吉贝克编码文本(bytes)的一个示例,该文本被错误的编码解码.在这种情况下,字符串最初被编码为UTF-8;重新编码为ISO-8859-1 (拉丁文-1)重新创建UTF-8字节,并且从UTF-8 (Python3中的默认值)解码产生预期的结果。
如果从外部源接收到这些mojibake字符串,则可以使用ISO-8859-1安全地对它们进行编码,以重新创建原始字节。字节-编码的文本-可以传递给chardet进行分析。
https://stackoverflow.com/questions/60998378
复制相似问题