我一直在努力用Python进行解码和编码,但我不太清楚如何解决我的问题。我在遍历显然是用utf-8编码的xml文本文件(sample),使用beautifulsoup来解析每个文件,然后查看文件中是否有句子包含两个不同单词列表中的一个或多个单词。因为xml文件来自18世纪,所以我需要保留xml中的em破折号。下面的代码可以做到这一点,但它还保留了一个讨厌的方框字符,我想删除它。我相信方框字符是this character。在
(您可以在上面的示例文件的第3682行中找到我希望删除的字符的示例。在这个网页上,这个字符看起来像一个'or'管道,但是当我读到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
我试图用
^{pr2}$但是Python抛出了一个错误标志:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 280: ordinal not in range(128)
有人知道如何从xml文件中删除这些框吗?我很感激别人能提供的任何帮助。在
在阅读示例时,以下是文档中的非ASCII字符:
^{pr2}$\u2223
是第3682行中的实际字符,它被用作软连字符。其他字符用于标记难以辨认的字符,例如:这里有一些代码可以执行您的代码尝试的操作。请确保使用Unicode进行处理:
输出:
试试看:
我想你只是少了那个多余的“\”
这也可能有用。在
^{pr2}$问题是你混合了}。每当您这样做时,Python必须将一个转换为另一个,这是通过使用
unicode
和{sys.getdefaultencoding()
来实现的,这通常是ASCII,这几乎永远不是您想要的。*如果异常来自这一行:
…修复很简单…除了您必须知道
^{pr2}$noextrawhitespace
应该是unicode
对象还是UTF-8编码str
对象)。如果是前者,那就是:如果是后者,那就是:
但实际上,您必须使代码中的所有字符串保持一致;将这两个字符串混合在一起会导致比这一个更大的问题。在
因为我没有您的XML文件要测试,所以我编写了自己的:
然后,我在代码的底部添加了这两行代码(在顶部加了一点,只需打开我的文件,而不必进行任何操作):
现在的输出是:
所以,我想这就是你想要的。在
*当然,有时你想要ASCII…但那通常不是你拥有
unicode
对象的时候相关问题 更多 >
编程相关推荐