我有一个我想要解析的 XML 文件的文件夹。我需要从这些文件的元素中获取文本。它们将被收集并打印到 CSV 文件中,其中的元素按列列出。
I can实际上现在就这样做some我的文件。也就是说,对于我的许多 XML 文件,该过程进展顺利,并且我得到了我想要的输出。执行此操作的代码是:
import os, re, csv, string, operator
import xml.etree.cElementTree as ET
import codecs
def parseEO(doc):
#getting the basic structure
tree = ET.ElementTree(file=doc)
root = tree.getroot()
agencycodes = []
rins = []
titles =[]
elements = [agencycodes, rins, titles]
#pulling in the text from the fields
for elem in tree.iter():
if elem.tag == "AGENCY_CODE":
agencycodes.append(int(elem.text))
elif elem.tag == "RIN":
rins.append(elem.text)
elif elem.tag == "TITLE":
titles.append(elem.text)
with open('parsetest.csv', 'w') as f:
writer = csv.writer(f)
writer.writerows(zip(*elements))
parseEO('EO_file.xml')
但是,在输入文件的某些版本上,我收到臭名昭著的错误:
'ascii' codec can't encode character u'\x97' in position 32: ordinal not in range(128)
完整的回溯是:
---------------------------------------------------------------------------
UnicodeEncodeError Traceback (most recent call last)
<ipython-input-15-28d095d44f02> in <module>()
----> 1 execfile(r'/parsingtest.py') # PYTHON-MODE
/Users/ian/Desktop/parsingtest.py in <module>()
91 writer.writerows(zip(*elements))
92
---> 93 parseEO('/EO_file.xml')
94
95
/parsingtest.py in parseEO(doc)
89 with open('parsetest.csv', 'w') as f:
90 writer = csv.writer(f)
---> 91 writer.writerows(zip(*elements))
92
93 parseEO('/EO_file.xml')
UnicodeEncodeError: 'ascii' codec can't encode character u'\x97' in position 32: ordinal not in range(128)
通过阅读其他线程,我相当有信心问题出在正在使用的编解码器中(而且,你知道,错误也很清楚)。但是,我读过的解决方案没有帮助me(强调是因为我知道我是问题的根源,而不是人们过去回答的方式)。
几种回应(例如:this one https://stackoverflow.com/questions/11285866/unicodeencodeerror-ascii-codec-cant-encode-character and this one https://stackoverflow.com/questions/1653569/unicodeencodeerror-ascii-codec-cant-encode-character?rq=1 and this one https://stackoverflow.com/questions/2513027/encoding-gives-ascii-codec-cant-encode-character-ordinal-not-in-range128)不直接处理 ElementTree,而且我不确定如何将解决方案转化为我正在做的事情。
其他处理 ElementTree 的解决方案(例如:this one https://stackoverflow.com/questions/13493477/unicodeencodeerror-ascii-codec-cant-encode-characters and this one https://stackoverflow.com/questions/12349728/elementtree-and-unicode)要么使用短字符串(此处的第一个链接),要么使用 ElementTree 中的 .tostring/.fromstring 方法,但我不这样做。 (当然,也许我应该这样做。)
我尝试过但不起作用的事情:
-
我尝试通过 UTF-8 编码引入文件:
infile = codecs.open('/EO_file.xml', encoding="utf-8")
parseEO(infile)
但我认为 ElementTree 进程已经将其理解为 UTF-8(在我拥有的所有 XML 文件的第一行中都注明了),因此这不仅不正确,而且实际上又是多余的错误。
-
我尝试在循环内声明一个编码过程,替换:
tree = ET.ElementTree(file=doc)
with
parser = ET.XMLParser(encoding="utf-8")
tree = ET.parse(doc, parser=parser)
在上面的循环中确实有效。这对我来说也不起作用。之前有效的相同文件仍然有效,造成错误的相同文件仍然会造成错误。
还有很多其他随机尝试,但我不会详细说明这一点。
因此,虽然我认为我所拥有的代码效率低下并且不利于良好的编程风格,但它确实满足了我对多个文件的要求。我试图了解是否只是缺少一个我不知道的参数,是否应该以某种方式预处理文件(我还没有确定有问题的字符在哪里,但确实知道你'\ x97 转换为某种控制字符),或其他一些选项。