Python перекодировать из utf 8 в windows 1251

Всем привет, не могу сконвертировать выходной файл в читабельный вид,кодировка ANSI,сам файл в utf-8:

import csv
def write_group_to_csv(data,filename,encoding='utf-8'):

     with open(filename,'w',newline='',encoding=encoding) as csvfile:
        fieldnames=['id','first_name','last_name','sex','bdate','city','country','mobile_phone','home_phone','skype','twitter','instagram','photo_200_orig','university_name','faculty_name','graduation','education_form','education_status','schools_name','schools_year_from','schools_year_to','relatives']
        writer=csv.DictWriter(csvfile,delimiter=';',fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(data)
        print('Data about group is written in',filename)
     csvfile.close

write_group_to_csv(G_idd,'123.csv')

Пробовал менять значение encoding по умолчанию на ANSI, выдает ошибку:

 UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: invalid character

Всем привет, не могу сконвертировать выходной файл в читабельный вид,кодировка ANSI,сам файл в utf-8:

import csv
def write_group_to_csv(data,filename,encoding='utf-8'):

     with open(filename,'w',newline='',encoding=encoding) as csvfile:
        fieldnames=['id','first_name','last_name','sex','bdate','city','country','mobile_phone','home_phone','skype','twitter','instagram','photo_200_orig','university_name','faculty_name','graduation','education_form','education_status','schools_name','schools_year_from','schools_year_to','relatives']
        writer=csv.DictWriter(csvfile,delimiter=';',fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(data)
        print('Data about group is written in',filename)
     csvfile.close

write_group_to_csv(G_idd,'123.csv')

Пробовал менять значение encoding по умолчанию на ANSI, выдает ошибку:

 UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: invalid character

45 / 39 / 24

Регистрация: 29.11.2013

Сообщений: 142

1

Как перекодировать строку?

21.12.2014, 18:13. Показов 20866. Ответов 6


Студворк — интернет-сервис помощи студентам

Как перекодировать эту строку в читаемый вид из cp1251 в utf-8?

ÀÍÅÊÄÎÒ — Ñåìüÿ.Ìóëüò.Ïîäðîáíåå



0



2740 / 2339 / 620

Регистрация: 19.03.2012

Сообщений: 8,830

21.12.2014, 18:30

2

Когда строка уже в виде крокозябр и начальная кодировка в которой все нормально отображается потеряна, то только с помощью сервисов типа http://www.artlebedev.ru/tools/decoder/



0



45 / 39 / 24

Регистрация: 29.11.2013

Сообщений: 142

21.12.2014, 18:39

 [ТС]

3

tsar925, А если начальная кодировка cp1251 ?



0



alex925

2740 / 2339 / 620

Регистрация: 19.03.2012

Сообщений: 8,830

21.12.2014, 18:45

4

Если в твоё приложение приходить строка в cp1251, то просто эту строку декодируешь во внутреннее представление строк (в utf8) и все.

Python
1
inp_str.decode('cp1251')



0



ivsatel

45 / 39 / 24

Регистрация: 29.11.2013

Сообщений: 142

21.12.2014, 19:06

 [ТС]

5

tsar925, Что-то делаю не так?

Python
1
2
a = "ÀÍÅÊÄÎÒ - Ñåìüÿ.Ìóëüò.Ïîäðîáíåå".encode('utf-8')
print(a.decode('cp1251'))

Кстати в браузере кракозябры четко преобразуются при сохранении поста.



0



2740 / 2339 / 620

Регистрация: 19.03.2012

Сообщений: 8,830

21.12.2014, 19:14

6

Вторая строка неправильная, у тебя за место cp1251 должно быть написано utf8, потому что метод decode принимает значение кодировки в которой закодирована строка сейчас.



1



ivsatel

45 / 39 / 24

Регистрация: 29.11.2013

Сообщений: 142

21.12.2014, 20:49

 [ТС]

7

Получилось вот так:

Python
1
print(inp_str.encode('latin1').decode('cp1251'))



0



Python is a popular programming language used for various purposes, from website development to data analysis. And one of the tasks often faced by developers is converting files from one encoding to another. In this article, we’ll discuss how to convert a file from UTF-8 to CP1251 or ANSI using Python.

First, let’s understand what encoding is. Encoding is the process of converting characters from one set of symbols (aka character set) to another. For example, a character «A» can be represented in many ways in different character sets. In UTF-8, it is represented by two bytes (0x41), while in CP1251 or ANSI, it is represented by a single byte (0x41).

Now, let’s dive into the code. There are two ways to accomplish this task — using the built-in codecs module or using a third-party library like chardet.

Using codecs module

The codecs module provides a set of methods to deal with various encodings. Here’s how you can use it to convert a file from UTF-8 to CP1251 or ANSI:

import codecs

# Define input and output files
input_file = 'utf8_file.txt'
output_file = 'cp1251_file.txt'

# Open input file in read mode and output file in write mode with CP1251 encoding
with codecs.open(input_file, mode='r', encoding='utf-8') as file_in:
    with codecs.open(output_file, mode='w', encoding='cp1251') as file_out:
        for line in file_in:
            file_out.write(line)

In this code, we are opening the input file in read mode with UTF-8 encoding and the output file in write mode with CP1251 encoding. Then we iterate over each line in the input file and write it to the output file.

Similarly, you can convert the file to ANSI encoding by replacing encoding in `codecs.open()` method to `cp1252`.

Using chardet library

The chardet library is a third-party library that can detect the encoding of a file. Here’s how you can use it to convert a file from UTF-8 to CP1251 or ANSI:

import chardet
import codecs

# Define input and output files
input_file = 'utf8_file.txt'
output_file = 'cp1251_file.txt'

# Open input file in read mode and detect encoding using chardet
with open(input_file, mode='rb') as file_in:
    encoding = chardet.detect(file_in.read())['encoding']

# Open input file in read mode using detected encoding and output file in write mode with CP1251 encoding
with codecs.open(input_file, mode='r', encoding=encoding) as file_in:
    with codecs.open(output_file, mode='w', encoding='cp1251') as file_out:
        for line in file_in:
            file_out.write(line)

In this code, we are first opening the input file in read mode with binary flag to read its raw contents. We use chardet.detect() method to detect the encoding of the file. Then we open the input file again with the detected encoding and output file with CP1251 encoding and write each line from input to output.

Similarly, you can convert the file to ANSI encoding by replacing encoding in the `codecs.open()` method to `cp1252`.

Conclusion

Converting files from one encoding to another is a common task for developers, and Python provides helpful tools to accomplish this. In this article, we discussed how to convert files from UTF-8 to CP1251 or ANSI using both built-in codecs module and third-party chardet library. Keep in mind that encoding detection is not always reliable, so it’s a good practice to confirm the encoding before proceeding with conversion.

Вечно путаюсь в этих кодировках, поэтому решил сделать себе памятку. Покажу на примере.

Итак, кодировка исходного кода задается в первой-второй строке:

#-*-coding: UTF-8 -*-

Далее, допустим мы парсим какой-то сайт в windows-1251:

raw_data = urllib.urlopen(«bla bla bla»).read()

Мы получили данные, и сейчас они находятся в кодировке 1251, а исходник в utf-8, и нам нужно воспользоватся регулярками с кириллицей чтобы что-нибудь найти, выражение:

data = re.findall(r’Данные.*?<.*?>(.*?)<\/>’, raw_data)

выдаст нам пустой массив, потомому что данные в 1251 а регулярка в utf-8. В питоне есть несколько функций для перекодирования:

decode(‘WINDOWS-1251’) — декодирует строку из кодировки 1251 в ЮНИКОД(ЮНИКОД != UTF-8)
encode(‘UTF-8’) — кодирует строку из юникода в UTF-8.

Что касается Юникод vs UTF-8, то:
UNICODE: u’\u041c\u0430\u043c\u0430 \u043c\u044b\u043b\u0430 \u0440\u0430\u043c\u0443′
UTF-8: ‘\xd0\x9c\xd0\xb0\xd0\xbc\xd0\xb0 \xd0\xbc\xd1\x8b\xd0\xbb\xd0\xb0 \xd1\x80\xd0\xb0\xd0\xbc\xd1\x83’
нормальный вид: ‘Мама мыла раму’

Итак, чтобы у нас не было проблем с кодировками, нам достаточно сделать вот так:

raw_data = urllib.urlopen(«bla bla bla»).read().decode(‘WINDOWS-1251’).encode(‘UTF-8’)

И теперь наша запарсеная страница в той же кодировке что и исходник программы, и можно смело использовать кириллицу в регулярках, или в других ваших решениях. Конечно это не единственное решение, но в моем случае самое простое и удобное.

  • Python скачать для windows 10 64 bit на русском официальный сайт
  • Python открыть файл в windows
  • Pycharm community edition для windows 7 x64
  • Python скрипт в фоновом режиме windows
  • Qbittorrent не качает простаивает windows 10