首页 > 解决方案 > 将 utf-8 字符串更改为 cp1251 (Python)

问题描述

我正在尝试将带有波兰字符(例如“ęśążćółń”)的 Excel 文件转换为普通字母“esazcoln”。首先,我已经设法将 xlsx 文件转换为 txt,然后:

f = open("PATH_TO_TXT_FILE")
r = f.read()
r.upper()
new_word = ""
for char in r:
    if char == "Ą":
        new_word += "A"
    elif char == "Ć":
        new_word += "C"
    elif char == "Ę":
        new_word += "E"
    elif char == "Ł":
        new_word += "L"
    elif char == "Ó":
        new_word += "O"
    elif char == "Ż"  "Ź":
        new_word += "Z"
    elif char == "Ź":
        new_word += "Z"
    elif char == "Ś":
        new_word += "S"
    else: 
        new_word += char

encoded_bytes = r.encode('utf-8', "replace")
decoded = encoded_bytes.decode(
    "cp1252", "replace")
print(decoded)

文件中写着:asdżółć

输出:asdżółć

我想收到:asdzolc

有没有人可以帮助我?

标签: python-3.xstringutf-8charcp1252

解决方案


我找不到从中获取模式/子模板的堆栈溢出页面,但这是一般的想法:

#!/usr/bin/env python3
# coding: UTF-8

import re


mapping = {
    'Ą': 'A',
    'Ć': 'C',
    'Ę': 'E',
    'Ł': 'L',
    'Ó': 'O',
    'Ż': 'Z',
    'Ź': 'Z',
    'Ś': 'S',

    'ą': 'a',
    'ć': 'c',
    'ę': 'e',
    'ł': 'l',
    'ó': 'o',
    'ż': 'z',
    'ź': 'z',
    'ś': 's',
}


pattern = re.compile("|".join(mapping.keys()))


def replace_by_mapping(text):
    return pattern.sub(lambda m: mapping[re.escape(m.group(0))], text)


if __name__ == '__main__':
    with open('polish_test.txt', 'r') as f:

        contents = f.read()
        contents = replace_by_mapping(contents)

        print(contents)

推荐阅读