我必须从几个xml文件中提取信息,其中一些包含韩语信息。该文件具有以下结构:
<?xml version="1.0" encoding="UTF-8"?>
<Root _ID="999" _Status="Closed">
<Name>Big tech</Name>
<LegalName>Big tech Inc.</LegalName>
<Comments> 섹터와 지역에 따라 대표적인 기업과 내재가치 대비 저평가</Comments>
....
</Root>
我的代码如下:
import xml.etree.ElementTree as ET
Company=open('Company.csv', 'w')
tree = ET.parse(xmlpath, parser=ET.XMLParser(encoding="utf-8"))#parserx=ET.XMLParser(encoding="cp949")
root = tree.getroot()
name=root.find('Name').text
legalname=root.find('LegalName').text
comments=root.find('Comments').text
Company.write('Name; LegalName;Comments;\n')
Company.write('{}; {}; {}\n'.format(name, legalname, comments))
Company.close()
我得到的错误如下:
Traceback (most recent call last):
File "ET.py", line 226, in <module>
Company.write('{}; {}; {}\n'.format(name, legalname, comments))
File "C:\Users\*****\*****\Local\Continuum\anaconda3\lib\encodings
\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position *2-**4:
character maps to <undefined>
当我使用以下行时:
comments=comments.encode('utf-8')
csv会记录此字符,而不是韩语字符:
b'\xec\x84\xb9\xed\x84\xb0\xec\x99\x80 \xec\xa7\x80\xec\x97\xad\xec\x97\x90 \xeb
\x94\xb0\xeb\x9d\xbc \xeb\x8c\x80\xed\x91\x9c\xec\xa0\x81\xec\x9d\xb8 \xea\xb8\x
b0\xec\x97\x85\xea\xb3\xbc \xeb\x82\xb4\xec\x9e\xac\xea\xb0\x80\xec\xb9\x98 \xeb
\x8c\x80\xeb\xb9\x84 \xec\xa0\x80\xed\x8f\x89\xea\xb0\x80'
我已经尝试过comments=comments.encode('utf-8').decode('utf-8')以及所有编码和解码组合(使用utf-8、cp1252、euc_-kr和cp949),但都没有成功,每当我尝试将行添加到csv文件时,我总是会收到以前的错误。如果xml不包含韩语字符,则不会出现错误
目前没有回答
相关问题 更多 >
编程相关推荐