使用 Python 从 xml 数据库中删除非 Unicode 字符
Remove non Unicode characters from xml database with Python
所以我有一个 9000 行 xml 的数据库,保存为 txt,我想在 python 中加载它,所以我可以做一些格式化并删除不必要的标签(我只需要一些的标签,但有很多不必要的信息)使其可读。但是,我得到一个 UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 608814: character maps to <undefined>
,我认为这意味着程序 运行 变成了一个非 Unicode 字符。我很确定这些字符对程序并不重要(我要查找的数据都是纯文本,没有特殊符号),所以当我无法读取时,如何从 txt 文件中删除所有这些字符文件没有得到 UnicodeDecodeError
?
一个粗略的解决方法是自己解码文件中的字节并指定错误处理。例如:
for line in somefile:
uline = line.decode('ascii', errors='ignore')
这会将行变成一个 Unicode 对象,其中所有非 ascii 字节都已被删除。这不是通常推荐的方法 - 理想情况下,您希望使用适当的解析器处理 XML,或者至少知道您的文件的编码并适当地打开它(具体细节取决于您的 Python 版本) .但是如果你完全确定你只关心 ascii 字符,这是一个简单的后备。
该错误表明您在使用 open()
函数时未指定显式字符编码。 locale.getpreferredencoding(False)
在这种情况下使用(例如,cp1252
)。该错误表明它不是适合输入的编码。
An xml document may contain a declaration at the very begining that specifies the encoding used explicitly. Otherwise the encoding is defined by BOM or it is utf-8. 如果您的复制粘贴和保存文件没有弄乱编码并且您没有看到诸如 <?xml version="1.0" encoding="iso-8859-1" ?>
之类的行,则使用 [=16= 打开文件]:
with open('input-xml-like.txt', encoding='utf-8', errors='ignore') as file:
...
如果输入是实际的 XML 则只需将其传递给 XML 解析器即可:
import xml.etree.ElementTree as etree
tree = etree.parse('input.xml')
所以我有一个 9000 行 xml 的数据库,保存为 txt,我想在 python 中加载它,所以我可以做一些格式化并删除不必要的标签(我只需要一些的标签,但有很多不必要的信息)使其可读。但是,我得到一个 UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 608814: character maps to <undefined>
,我认为这意味着程序 运行 变成了一个非 Unicode 字符。我很确定这些字符对程序并不重要(我要查找的数据都是纯文本,没有特殊符号),所以当我无法读取时,如何从 txt 文件中删除所有这些字符文件没有得到 UnicodeDecodeError
?
一个粗略的解决方法是自己解码文件中的字节并指定错误处理。例如:
for line in somefile:
uline = line.decode('ascii', errors='ignore')
这会将行变成一个 Unicode 对象,其中所有非 ascii 字节都已被删除。这不是通常推荐的方法 - 理想情况下,您希望使用适当的解析器处理 XML,或者至少知道您的文件的编码并适当地打开它(具体细节取决于您的 Python 版本) .但是如果你完全确定你只关心 ascii 字符,这是一个简单的后备。
该错误表明您在使用 open()
函数时未指定显式字符编码。 locale.getpreferredencoding(False)
在这种情况下使用(例如,cp1252
)。该错误表明它不是适合输入的编码。
An xml document may contain a declaration at the very begining that specifies the encoding used explicitly. Otherwise the encoding is defined by BOM or it is utf-8. 如果您的复制粘贴和保存文件没有弄乱编码并且您没有看到诸如 <?xml version="1.0" encoding="iso-8859-1" ?>
之类的行,则使用 [=16= 打开文件]:
with open('input-xml-like.txt', encoding='utf-8', errors='ignore') as file:
...
如果输入是实际的 XML 则只需将其传递给 XML 解析器即可:
import xml.etree.ElementTree as etree
tree = etree.parse('input.xml')