我有包含许多UTF-8 xml文件的zip存档.这些文件主要包含英文标签和文本,但有些标签包含非英文文本.我打开zip文件并解析其中的xml文件没有问题,但是非英文文本丢失了它的编码.
当在Notepad ++中提取并打开xml文件时,非英语文本如下所示:
???? ?????????? ? ??????? ?? ????????? ?? ?????????? ????????????? ???????? ????? (????) - 176.100.
Run Code Online (Sandbox Code Playgroud)
当它被Python(在linux盒子上)提取和读取时,文本看起来像:
ÐÑÑÑ ÐºÐ°ÑбованÑа к доллаÑÑ Ð½Ðµ изменилÑÑ Ð½Ð° УкÑаинÑкой ÐежбанковÑкой ÐалÑÑной ÐиÑже (УÐÐÐ) - 176.100.
Run Code Online (Sandbox Code Playgroud)
我的代码看起来像:
def parse(self, fp):
# open/decompress zip file
with zipfile.ZipFile(fp, 'r') as f:
# get all files in zip
comp_files = f.namelist()
for comp_file in comp_files:
cfp = f.open(comp_file, 'r')
# parse xml
tree = ElementTree.parse(cfp)
...parsing...
Run Code Online (Sandbox Code Playgroud)
我尝试解码/编码来自cfp的文本,并用codecs.EncodedFile()和utf_8和utf_8_sig的输入编码包装,没有任何变化.我该怎么做来修复非英文文本?
您看到的结果是UTF-8被错误地解码为latin-1/iso-8859-1:
>>> x=u'???? ?????????? ? ??????? ?? ????????? ?? ?????????? ????????????? ???????? ????? (????) - 176.100.'
>>> print x.encode('utf8').decode('latin1')
ÐÑÑÑ ÐºÐ°ÑбованÑа к доллаÑÑ Ð½Ðµ изменилÑÑ Ð½Ð° УкÑаинÑкой ÐежбанковÑкой ÐалÑÑной ÐиÑже (УÐÐÐ) - 176.100.
Run Code Online (Sandbox Code Playgroud)
我保存了以下通过Notepad ++编码的文本,如在zipfile中编码为UTF-8而没有BOM的单个文件:
<text>???? ?????????? ? ??????? ?? ????????? ?? ?????????? ????????????? ???????? ????? (????) - 176.100.</text>
Run Code Online (Sandbox Code Playgroud)
您的代码经过修改以使其可运行:
from xml.etree import ElementTree
import zipfile
def parse(fp):
# open/decompress zip file
with zipfile.ZipFile(fp, 'r') as f:
# get all files in zip
comp_files = f.namelist()
for comp_file in comp_files:
cfp = f.open(comp_file, 'r')
# parse xml
tree = ElementTree.parse(cfp)
print tree.getroot().text
print type(tree.getroot().text)
parse(open('file.zip'))
Run Code Online (Sandbox Code Playgroud)
结果:
???? ?????????? ? ??????? ?? ????????? ?? ?????????? ????????????? ???????? ????? (????) - 176.100.
<type 'unicode'>
Run Code Online (Sandbox Code Playgroud)
因此,我认为它只是在Linux机器上显示不正确,但如果没有您正在使用的文件的实际样本,则很难进一步分析.
| 归档时间: |
|
| 查看次数: |
3129 次 |
| 最近记录: |