duh*_*ime 3 python xml string unicode ascii
我一直在努力解决 Python 中的解码和编码问题,但我不太清楚如何解决我的问题。我正在循环遍历明显以 utf-8 编码的 xml 文本文件(示例),使用 Beautiful Soup 解析每个文件,然后查看文件中的任何句子是否包含两个不同单词列表中的一个或多个单词。因为 xml 文件来自 18 世纪,所以我需要保留 xml 中的长破折号。下面的代码做得很好,但它还保留了一个我希望删除的讨厌的框字符。我相信盒子字符就是这个字符。
(您可以在上面示例文件的第 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
Run Code Online (Sandbox Code Playgroud)
我尝试使用以下方法删除盒子
noboxes = noextrawhitespace.replace(u"\u2610", "")
Run Code Online (Sandbox Code Playgroud)
但是Python抛出了一个错误标志:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 280: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
有谁知道如何从 xml 文件中删除框?对于其他人可以提供的任何帮助,我将不胜感激。
尝试一下:
noextrawhitespace.replace("\\u2610", "")
Run Code Online (Sandbox Code Playgroud)
我认为你只是缺少那个额外的“\”
这也可能有效。
print(noextrawhitespace.decode('unicode_escape').encode('ascii','ignore'))
Run Code Online (Sandbox Code Playgroud)