Python | Кодировка символов
Finding the text which is having nonstandard character encoding is a very common step to perform in text processing.
All the text would have been from utf-8 or ASCII encoding ideally but this might not be the case always. So, in such cases when the encoding is not known, such non-encoded text has to be detected and the be converted to a standard encoding. So, this step is important before processing the text further.
Charade Installation :
For performing the detection and conversion of encoding, charade – a Python library is required. This module can be simply installed using sudo easy_install charade or pip install charade.
Let’s see the wrapper function around the charade module.
Code : encoding.detect(string), to detect the encoding
Python3
# -*- coding: utf-8 -*-import charadedef detect(s): try: # check it in the charade list if isinstance(s, str): return charade.detect(s.encode()) # detecting the string else: return charade.detect(s) # in case of error # encode with "utf -8" encoding except UnicodeDecodeError: return charade.detect(s.encode("utf-8")) |
Функции обнаружения возвращают 2 атрибута:
Уверенность: вероятность того, что шарада окажется правильной. Кодировка: какая это кодировка.
Code : encoding.convert(string) to convert the encoding.
Python3
# -*- coding: utf-8 -*-import charadedef convert(s): # if in the charade instance if isinstance(s, str): s = s.encode() # retrieving the encoding information # from the detect() output encode = detect(s)["encoding"] if encode == "utf-8": return s.decode() else: return s.decode(encoding) |
Code : Example
Python3
# importing libraryimport encodingd1 = encoding.detect("geek")print ("d1 is encoded as : ", d1)d2 = encoding.detect("ascii")print ("d2 is encoded as : ", d2) |
Выход :
d1 is encoded as : (confidence": 0.505, "encoding": "utf-8")
d2 is encoded as : ("confidence": 1.0, "encoding": "ascii")detect (): это оболочка charade.detect (). Он кодирует строки и обрабатывает исключения UnicodeDecodeError. Он ожидает байтовый объект, поэтому строка кодируется перед попыткой обнаружения кодировки.
convert (): это оболочка charade.convert (). Сначала он вызывает detect (), чтобы получить кодировку. Затем он возвращает декодированную строку.
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.