我有一个xml文件目录,其中xml文件的格式为:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="CoreNLP-to-HTML.xsl" type="text/xsl"?>
<root>
<document>
<sentences>
<sentence id="1">
<tokens>
<token id="1">
<word>Brand</word>
<lemma>brand</lemma>
<CharacterOffsetBegin>0</CharacterOffsetBegin>
<CharacterOffsetEnd>5</CharacterOffsetEnd>
<POS>NN</POS>
<NER>O</NER>
</token>
<token id="2">
<word>Blogs</word>
<lemma>blog</lemma>
<CharacterOffsetBegin>6</CharacterOffsetBegin>
<CharacterOffsetEnd>11</CharacterOffsetEnd>
<POS>NNS</POS>
<NER>O</NER>
</token>
<token id="3">
<word>Capture</word>
<lemma>capture</lemma>
<CharacterOffsetBegin>12</CharacterOffsetBegin>
<CharacterOffsetEnd>19</CharacterOffsetEnd>
<POS>VBP</POS>
<NER>O</NER>
</token>
我解析每个xml文件并在标记之间存储单词,然后找到前100个单词。在
我是这样做的:
^{pr2}$但是,我得到了一个错误:
File "prac31.py", line 898, in main
v = find_top_words('/home/xyz/xml_dir')
File "prac31.py", line 43, in find_top_words
file_list.append(str(word.string.strip()))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 2: ordinal not in range(128)
这意味着什么?如何修复它?在
函数对ascii编解码器进行编码,
word.string.strip()
不返回ascii字符,因此在xml文件的某些地方,您可以捕捉到这个错误。解决方案是使用:要返回此值,您需要执行以下操作:
^{pr2}$希望有帮助。在
在这行代码中:
为什么要使用
str
?数据是Unicode,您可以将Unicode字符串附加到列表中。如果需要bytestring,那么可以使用word.string.strip().encode('utf8')
。在不要用beauthoulsoup,它完全不推荐使用。为什么不是标准库?如果您想要更复杂的xml处理,您可以使用lxml(但我确信您不会这样做)
它会很容易地解决你的问题。在
编辑: 忘了预告答案那是坏的-_- 您的问题是python2中的str(my_string)如果my_string包含非ascii字符,因为python2中unicode字符串上的str()就像试图编码为ascii一样,请改用encode('utf-8')方法。在
相关问题 更多 >
编程相关推荐