Problème avec les chardet depuis passage en V3
Bonjour tout le monde,
J'ai une fonction qui marche bien en V2 mais depuis que je suis passé en V3 ça ne marche plus.
Code:
1 2 3 4 5 6 7 8
| def get_file_encoding(filepath):
raw_data = open(filepath, "r").read() # chardet is not compatible with context manager
result = chardet.detect(raw_data)
if result.get('confidence') > .5:
char_enc = result.get('encoding')
else:
char_enc = 'utf-8'
return char_enc |
J'ai le message :
Expected object of type bytes or bytearray, got: <class 'str'>
En fouillant, j'ai trouvé d'où ce message venait :
Code:
1 2 3 4 5 6 7 8 9 10 11
| def detect(byte_str):
"""
Detect the encoding of the given byte string.
:param byte_str: The byte sequence to examine.
:type byte_str: ``bytes`` or ``bytearray``
"""
if not isinstance(byte_str, bytearray):
if not isinstance(byte_str, bytes):
raise TypeError('Expected object of type bytes or bytearray, got: '
'{0}'.format(type(byte_str))) |
(code tiré de la librairie)
Le problème est donc qu'il attend un type byte et là c'est vu en string.
j'ai alors essayé de convertir en bytes mais que neni :
Code:
result = chardet.detect(str.encode(raw_data))
Donne :
Citation:
'str' object has no attribute 'decode'
Voyez-vous comment je peux faire marcher cette fonction en python V3 SVP ? Je ne vois plus comment faire ?
D'avance, merci pour votre réponse et aide !!