【发布时间】:2013-10-31 23:19:18
【问题描述】:
我一直在努力解决 Python 中的解码和编码问题,但我不知道如何解决我的问题。我正在遍历显然用 utf-8 编码的 xml 文本文件 (sample),使用 Beautiful Soup 解析每个文件,然后查看文件中的任何句子是否包含来自两个不同单词列表的一个或多个单词.因为 xml 文件来自 18 世纪,所以我需要保留 xml 中的破折号。下面的代码可以很好地做到这一点,但它也保留了我希望删除的讨厌的框字符。我相信方框字符是this character。
(您可以在上面示例文件的第 3682 行找到我希望删除的字符的示例。在此网页上,该字符看起来像一个“或”管道,但是当我在 Komodo 中读取 xml 文件时,它看起来像一个框。当我尝试将该框复制并粘贴到搜索引擎中时,它看起来像一个“或”管道。但是,当我打印到控制台时,该字符看起来像一个空框。)
总而言之,下面的代码运行没有错误,但它打印出我想删除的空框字符。
for work in glob.glob(pathtofiles):
openfile = open(work)
readfile = openfile.read()
stringfile = str(readfile)
decodefile = stringfile.decode('utf-8', 'strict') #is this the dodgy line?
soup = BeautifulSoup(decodefile)
textwithtags = soup.findAll('text')
textwithtagsasstring = str(textwithtags)
#this method strips everything between anglebrackets as it should
textwithouttags = stripTags(textwithtagsasstring)
#clean text
nonewlines = textwithouttags.replace("\n", " ")
noextrawhitespace = re.sub(' +',' ', nonewlines)
print noextrawhitespace #the boxes appear
我尝试使用删除框
noboxes = noextrawhitespace.replace(u"\u2610", "")
但是 Python 抛出了一个错误标志:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 280: ordinal not in range(128)
有谁知道如何从 xml 文件中删除这些框?如果其他人可以提供任何帮助,我将不胜感激。
【问题讨论】:
-
哇,谁在 18 世纪生成 XML 文件?莱布尼茨?
-
(确实是莱布尼茨,但牛顿击败了他。)
-
同时,
str(readfile)应该做什么?文件上的read方法已经返回str。 -
U+2610 的有趣之处在于它应该是一个empty ballot box,但在许多字体中它并不存在,这意味着它被打印为一个缺少字符的空框,这很难区分。 (一些画线和其他空框字符也有类似的问题。)
标签: python xml string unicode ascii