我一直在努力用 Python 进行解码和编码,但我不太清楚如何解决我的问题。我正在遍历显然用 utf-8 编码的 xml 文本文件(示例),使用 Beautiful Soup 解析每个文件,然后查看文件中的任何句子是否包含来自两个不同单词列表的一个或多个单词。因为 xml 文件来自 18 世纪,所以我需要保留 xml 中的破折号。下面的代码很好地做到了这一点,但它也保留了我希望删除的讨厌的框字符。我相信盒子字符就是这个字符。
(您可以在上面示例文件的第 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 文件中删除这些框?对于其他人可以提供的任何帮助,我将不胜感激。