【问题标题】:Converting accented characters into latin without compromising ElementTree [duplicate]在不影响 ElementTree 的情况下将重音字符转换为拉丁语 [重复]
【发布时间】:2018-05-16 12:52:07
【问题描述】:

我试图弄清楚如何将所有重音字符(åéí...)替换为它们的拉丁对应字符(分别为aei ) 并且我尝试了几种方法来做到这一点,但它们都做了超出我理解范围的事情,这使得 ElementTree 以后无法使用.fromstring() 进行转换。

我还必须转义 & 字符,但我已经想通了。

相关语法:

# -- coding: utf-8 --

import xml.etree.ElementTree as ET
import os
import re

path = "C:\\Users\\SuperUser\\Desktop\\audit\\audit\\saved\\audit"

root = ET.Element("root")

for filename in os.listdir(path):
    with open(path + "\\" + filename) as myfile:
        lines = myfile.readlines()

    for line in lines:
        line = re.sub(r"&(?!#\d{3};|amp;)", "&", line)
        xmlVal = ET.fromstring(line)

错误发生在最后一行,与其他解决方案一起抱怨UnicodeEncodeError: 'ascii' codec can't encode character u'\xc4' in position 161: ordinal not in range(128) 或类似错误。

【问题讨论】:

  • 请注意,链接问题中的this answer 显示了如何使用标准unicodedata 模块“手动”执行此操作。

标签: python regex ascii encode elementtree


【解决方案1】:

尝试使用 unidecode 模块

例如:

import xml.etree.ElementTree as ET
import os
import re
import unidecode


path = "C:\\Users\\SuperUser\\Desktop\\audit\\audit\\saved\\audit"

root = ET.Element("root")

for filename in os.listdir(path):
    with open(path + "\\" + filename) as myfile:
        lines = myfile.readlines()

    for line in lines:
        line = unidecode.unidecode(line)
        xmlVal = ET.fromstring(line)

【讨论】:

    猜你喜欢
    • 2019-07-27
    • 1970-01-01
    • 2023-02-07
    • 2020-09-20
    • 2022-01-20
    • 2021-08-01
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    相关资源
    最近更新 更多