Unicodedecodeerror python 3 charmap

Кодировка текстового документа

Доброго времени суток! Имеется программа для замены кириллицы на латиницу и записи в новый файл. Проблема в том, что не все текстовые файлы получается преобразовать.
Сталкиваюсь с ошибкой:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
dic = {'А':'A', 'а':'a', 'Ә':'Á', 'ә':'á', 'Б':'B', 'б':'b', 'Д':'D', 'д':'d', 'Е':'E', 'е':'e', 'Ф':'F', 'ф':'f', 'Ғ':'Ǵ', 'ғ':'ǵ', 'Г':'G', 'г':'g', 'Х':'H', 'х':'h', 'І':'I', 'і':'i', 'И':'I', 'и':'ı', 'Й':'I', 'й':'ı', 'Һ':'H', 'һ':'h', 'Ж':'J', 'ж':'j', 'К':'K', 'к':'k', 'Л':'L', 'л':'l', 'М':'M', 'м':'m', 'Н':'N', 'н':'n', 'Ң':'Ń', 'ң':'ń', 'О':'O', 'о':'o', 'Ө':'Ó', 'ө':'ó', 'П':'P', 'п':'p', 'Қ':'Q', 'қ':'q', 'Р':'R', 'р':'r', 'Ш':'Sh', 'ш':'sh', 'С':'S', 'с':'s', 'Т':'T', 'т':'t', 'Ұ':'U', 'ұ':'u', 'Ү':'Ú', 'ү':'ú', 'В':'V', 'в':'v', 'Ы':'Y', 'ы':'y', 'У':'Ý', 'у':'ý', 'З':'Z', 'з':'z', 'Ч':'Ch', 'ч':'ch', 'Э':'E', 'э':'e', 'Щ':'', 'щ':'', 'Ь':'','ь':'', 'Ъ':'', 'ъ':'', 'Я':'Ia','я':'ia' } alphabet = ['А', 'а', 'Ә', 'ә', 'Б', 'б', 'Д', 'д', 'Е', 'е', 'Ф', 'ф', 'Ғ', 'ғ', 'Г', 'г', 'Х', 'х', 'І', 'і', 'И', 'и', 'Й', 'й', 'Һ', 'һ', 'Ж', 'ж', 'К', 'к', 'Л', 'л', 'М', 'м', 'Н', 'н', 'Ң', 'ң', 'О', 'о', 'Ө', 'ө', 'П', 'п', 'Қ', 'қ', 'Р', 'р', 'Ш', 'ш', 'С', 'с', 'Т', 'т', 'Ұ', 'ұ', 'Ү', 'ү', 'В', 'в', 'Ы', 'ы', 'У', 'у', 'З', 'з', 'Ч', 'ч', 'Э', 'э', 'Щ', 'щ', 'Ь', 'ь', 'Ъ', 'ъ', 'Я','я'] with open('text.docx', 'r', encoding="utf-8") as f: lines = f.read() file = open('text2.docx', "w") for line in lines: file.write((''.join([dic.get(char, char) for char in line]))) file = open ('text2.docx', "r") print(file.read()) file.close()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
import textract dic = {'А':'A', 'а':'a', 'Ә':'Á', 'ә':'á', 'Б':'B', 'б':'b', 'Д':'D', 'д':'d', 'Е':'E', 'е':'e', 'Ф':'F', 'ф':'f', 'Ғ':'Ǵ', 'ғ':'ǵ', 'Г':'G', 'г':'g', 'Х':'H', 'х':'h', 'І':'I', 'і':'i', 'И':'I', 'и':'ı', 'Й':'I', 'й':'ı', 'Һ':'H', 'һ':'h', 'Ж':'J', 'ж':'j', 'К':'K', 'к':'k', 'Л':'L', 'л':'l', 'М':'M', 'м':'m', 'Н':'N', 'н':'n', 'Ң':'Ń', 'ң':'ń', 'О':'O', 'о':'o', 'Ө':'Ó', 'ө':'ó', 'П':'P', 'п':'p', 'Қ':'Q', 'қ':'q', 'Р':'R', 'р':'r', 'Ш':'Sh', 'ш':'sh', 'С':'S', 'с':'s', 'Т':'T', 'т':'t', 'Ұ':'U', 'ұ':'u', 'Ү':'Ú', 'ү':'ú', 'В':'V', 'в':'v', 'Ы':'Y', 'ы':'y', 'У':'Ý', 'у':'ý', 'З':'Z', 'з':'z', 'Ч':'Ch', 'ч':'ch', 'Э':'E', 'э':'e', 'Щ':'', 'щ':'', 'Ь':'','ь':'', 'Ъ':'', 'ъ':'', 'Я':'Ia','я':'ia' } alphabet = ['А', 'а', 'Ә', 'ә', 'Б', 'б', 'Д', 'д', 'Е', 'е', 'Ф', 'ф', 'Ғ', 'ғ', 'Г', 'г', 'Х', 'х', 'І', 'і', 'И', 'и', 'Й', 'й', 'Һ', 'һ', 'Ж', 'ж', 'К', 'к', 'Л', 'л', 'М', 'м', 'Н', 'н', 'Ң', 'ң', 'О', 'о', 'Ө', 'ө', 'П', 'п', 'Қ', 'қ', 'Р', 'р', 'Ш', 'ш', 'С', 'с', 'Т', 'т', 'Ұ', 'ұ', 'Ү', 'ү', 'В', 'в', 'Ы', 'ы', 'У', 'у', 'З', 'з', 'Ч', 'ч', 'Э', 'э', 'Щ', 'щ', 'Ь', 'ь', 'Ъ', 'ъ', 'Я','я'] text = textract.process('text.docx') file = open('text3.docx', "wb") file.write(text) file = open('text3.docx', 'r') lines = file.read() file = open('text2.docx', "w") for line in lines: file.write((''.join([dic.get(char, char) for char in line]))) file = open ('text2.docx', "r") print(file.read()) file.close()

Открытие простого текстового документа
Привет. Начал изучать Python и наткнулся на ошибку, непонятно откуда взявшуюся. Как это исправить?

Читайте также:  Unexpected error java io ioexception

Удалить строки из текстового документа
Доброго времени суток. Есть текстовый документ, в нем сохранена информация по строкам. Большая.

Как получать и сохранять данные из списка текстового документа?
Приветствую Всех Друзья! Помогите пожалуйста не особо силен в программирование. Нужно изменить код.

Решение примера из текстового документа
Нужно сделать программу, решающую пример из текстового документа Я сделал вот так: with.

Кто Вам сказал, что .docx это текстовый файл? Ради интереса попробуйте заменить расширение .docx на .zip и открыть файл в архиваторе, много нового узнаете.

Хорошо. Прошу прощения в названии темы я ошибся. Признаю свою ошибку. Но сути проблемы это не решает.

Эксперт Python

ЦитатаСообщение от Squbble Посмотреть сообщение

Если файл содержит текст — то он закодирован определенной кодировкой.
Кодировку файла нужно указывать при открытии функцией open. Если указать неверную — получите ошибку декодирования.
По умолчанию на windows используется локаль пользователя, что равно для русской локализации windows-1251.
Это решает суть проблемы?

with open('text.docx', 'r', encoding="windows-1251") as f:

ЦитатаСообщение от Garry Galler Посмотреть сообщение

Однако файлы .docx не содержат текст, т.к. это zip-архивы, внутри которых находятся не только текстовые .xml, но и могут быть прикрепленные к документу картинки, например. Нет смысла открывать файл .docx как текстовый, какую бы кодировку ни выбрали.

ЦитатаСообщение от Squbble Посмотреть сообщение

Тогда в итоге в чем заключается ваша задача? Если я правильно понял, то обрабатывать необходимо не текстовые файлы, а документы Word.

(1) использовать python-docx, но тут придется разбираться со структурой документа.

(2) python довольно просто умеет работать с zip-архивами. Извлечь text.docx/word/document.xml, обработать как текстовый файл, а затем обновить его в архиве.

ЦитатаСообщение от valen10 Посмотреть сообщение

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
from zipfile import ZipFile import os import tempfile dic = {'А' : 'A', 'а' : 'a', 'Ф' : 'F', 'ф' : 'f', 'В' : 'V', 'в' : 'v'} with tempfile.TemporaryDirectory(prefix='my-encoder-') as tempdir: # Распаковка документа во временную папку. doc_x = ZipFile('test.docx') doc_x.extractall(tempdir) doc_x.close() # Обработка файла, содержащего текст документа, как текстового. doc_xml = open(os.path.join(tempdir, 'word', 'document.xml')) new_xml = '' for line in doc_xml: for char in line: if char in dic.keys(): new_xml += dic[char] else: new_xml += char new_xml += '\n' doc_xml.close() # Запись нового содержимого. doc_xml = open(os.path.join(tempdir, 'word', 'document.xml'), mode='w') doc_xml.write(new_xml) doc_xml.close() # Сборка нового документа. doc2_x = ZipFile('res.docx', mode='w') for root, dirs, files in os.walk(tempdir): for file in files: abs_path = os.path.join(root, file) rel_path = os.path.relpath(os.path.join(root, file), tempdir) doc2_x.write(abs_path, rel_path) doc2_x.close()

Не обращайте внимания на стиль написания программы, это далеко не python-стиль, тут главное идея.

Если пойти дальше, то .xml тоже можно обработать не как текст, а как структуру. Подробнее тут.

Эксперт Python

ЦитатаСообщение от valen10 Посмотреть сообщение

Я в курсе про формат — ТС’у я лишь пытался подсказать по работе с кодировками текстовых файлов. Но он все равно не понял, не смотря на ваше предыдущее пояснение про docx.
Тяжелый случай

ЦитатаСообщение от Garry Galler Посмотреть сообщение

ТС’у я лишь пытался подсказать по работе с кодировками текстовых файлов. Но он все равно не понял, не смотря на ваше предыдущее пояснение про docx.
Тяжелый случай

Все я понял, я признал свою ошибку в названии темы. Суть темы в открытии файла docx. Извините, но Ваши советы мне ничего не дали

Добавлено через 30 минут

ЦитатаСообщение от valen10 Посмотреть сообщение

Traceback (most recent call last):
File «test_doc.py», line 24, in
for line in doc_xml:
File «C:\Users\Home\AppData\Local\Programs\Python\Python37-32\lib\encodings\cp1251.py», line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: ‘charmap’ codec can’t decode byte 0x98 in position 2231: character maps to

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File «test_doc.py», line 45, in
doc2_x.write(abs_path, rel_path)
File «C:\Users\Home\AppData\Local\Programs\Python\Python37-32\lib\tempfile.py», line 805, in __exit__
self.cleanup()
File «C:\Users\Home\AppData\Local\Programs\Python\Python37-32\lib\tempfile.py», line 809, in cleanup
_shutil.rmtree(self.name)
File «C:\Users\Home\AppData\Local\Programs\Python\Python37-32\lib\shutil.py», line 507, in rmtree
return _rmtree_unsafe(path, onerror)
File «C:\Users\Home\AppData\Local\Programs\Python\Python37-32\lib\shutil.py», line 386, in _rmtree_unsafe
_rmtree_unsafe(fullname, onerror)
File «C:\Users\Home\AppData\Local\Programs\Python\Python37-32\lib\shutil.py», line 391, in _rmtree_unsafe
onerror(os.unlink, fullname, sys.exc_info())
File «C:\Users\Home\AppData\Local\Programs\Python\Python37-32\lib\shutil.py», line 389, in _rmtree_unsafe
os.unlink(fullname)
PermissionError: [WinError 32] Процесс не может получить доступ к файлу, так как этот файл занят другим процессом: ‘C:\\Users\\Home\\AppData\\Local\\Temp\\my-encoder-sx4agc1q\\word\\document.xml’

Источник

How To Solve Error “UnicodeDecodeError: ‘charmap’ codec can’t decode byte” In Python

UnicodeDecodeError: ‘charmap’ codec can’t decode byte

“UnicodeDecodeError: ‘charmap’ codec can’t decode byte” is a common error related to reading a text file. The below explanations can help you know more about the cause of this error and solutions.

How does the error “UnicodeDecodeError: ‘charmap’ codec can’t decode byte” happen?

The error is related to the file reader. You will get this error while requesting to read a text file containing some characters that are not encoded in the declared codec.

This error indicates that the decoding process could not be completed successfully. It may be because you have used a codec that cannot decode the texts you are reading. For example, you write the string to a file using utf-8 codec and then read a file with a different codec:

f = open("demo", "a", encoding="utf-8") f.write("𝘈𝘈") f.close() f = open("demo", "r", encoding="windows-1252") txt = f.read()
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 1023: character maps to

In general, the error occurs because your codec given doesn’t support decoding one or some characters in your strings into bytes that can be written print to the terminal. In some cases, the error message may be different, for instance:

f = open("demo", "a", encoding="utf-8") f.write("𝘈𝘈") f.close() f = open("demo", "r", encoding="utf-7") txt = f.read()
UnicodeDecodeError: 'utf7' codec can't decode byte 0xc3 in position 0: unexpected special character

How to solve this error?

Use another type of codec to decode characters

You must specify the correct encoding (mostly utf-8) when encoding and decoding the string into bytes or reading/writing it from/to the file.

f = open("demo", "a", encoding="utf-8") f.write("𝘈𝘈") f.close() f = open("demo", "r", encoding="utf-8") txt = f.read()

Replace the incorrect char at the error position

Another way to overcome this problem is to delete the character that caused the error at the position in your error message. If you don’t want to delete the incorrect character, you can change it to some character in the Latin alphabet that doesn’t have any accent:

f = open("demo", "a", encoding="utf-8") f.write("AA") f.close() f = open("demo", "r", encoding="utf-8") txt = f.read() print(txt)

Summary

“UnicodeDecodeError: ‘charmap’ codec can’t decode byte” error occurs when encountering a UTF-8 character which is not supported by the current encoding. When saving a text file or reading it, checking for the UTF-8 codec is always recommended so that the encoding can be propagated to avoid such a trivial problem, as it wastes a lot of time to fix.

Maybe you are interested:

I’m Edward Anderson. My current job is as a programmer. I’m majoring in information technology and 5 years of programming expertise. Python, C, C++, Javascript, Java, HTML, CSS, and R are my strong suits. Let me know if you have any questions about these programming languages.

Name of the university: HCMUT
Major: CS
Programming Languages: Python, C, C++, Javascript, Java, HTML, CSS, R

Источник

Оцените статью