python-3.x - 将 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
有没有人可以帮助我?
解决方案
我找不到从中获取模式/子模板的堆栈溢出页面,但这是一般的想法:
#!/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)
推荐阅读
- vb.net - 在 VB.NET 中使用 Google YouTube Data API 获取 YouTube 频道数据
- r - 无论文档边界如何,都可以有效地计算大型语料库中的词频
- c++ - 在 Rcpp (Armadillo) 函数中使用数字序列作为默认参数
- mysql - 查询此 Department-Employee 表以获取具有确切员工的部门的最佳方法是什么?
- arrays - 没有malloc的动态数组?
- angular - 单行 2 个离子项目,右侧第 3 个
- sql - 根据另一个表中的条目数在一个表中设置一个值
- python - 如何获得具有偶数/奇数/第 k 行总和的新列?
- c++ - + 运算符重载错误,即使它已重载
- python - 将 streamlit 应用程序转换为 pyinstaller 可执行文件