Skip to main content
 首页 » 编程设计

Python:从字符串中删除特定字符 (u"\u2610")

2025年05月04日29tuyile006

我一直在努力解决 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 文件中删除框?如果其他人可以提供任何帮助,我将不胜感激。

请您参考如下方法:

问题是您混合了 unicode 和 str。每当您这样做时,Python 都必须将一个转换为另一个,这是通过使用 sys.getdefaultencoding() 完成的,它通常是 ASCII,这几乎不是您想要的。*

如果异常来自这一行:

noboxes = noextrawhitespace.replace(u"\u2610", "") 

……修复很简单……除了您必须知道 noextrawhitespace 应该是 unicode 对象还是 UTF-8 编码 str 对象)。如果是前者,它是这样的:

noboxes = noextrawhitespace.replace(u"\u2610", u"") 

如果是后者,就是这样:

noboxes = noextrawhitespace.replace(u"\u2610".encode('utf-8'), "") 

但实际上,您必须使代码中的所有字符串保持一致;将两者混在一起会在更多地方引起问题。


由于我没有要测试的 XML 文件,所以我编写了自己的文件:

<xml> 
    <text>abc&#9744;def</text> 
</xml> 

然后,我将这两行添加到您的代码底部(还有一点添加到顶部以打开我的文件而不是通配符进行任何操作):

noboxes = noextrawhitespace.replace(u"\u2610".encode('utf-8'), "") 
print noboxes 

现在的输出是:

[<text>abc☐def</text>] 
[<text>abc☐def</text>] 
[<text>abcdef</text>] 

所以,我认为这就是您想要的。


* 当然,有时您需要 ASCII……但那些通常不是您拥有 unicode 对象的时候……