【问题标题】:How to remove certain utf-8 characters from a string?如何从字符串中删除某些 utf-8 字符?
【发布时间】:2019-04-30 16:42:41
【问题描述】:

就我而言,我想专门从字符串中删除 字符。我使用 BeautifulSoup 来解析某些 html 段落,并从中获取子字符串。到目前为止,我的代码如下所示:

# -*- coding: cp1252 -*-
from bs4 import BeautifulSoup as bs
import re

soup = bs(open("file.xhtml"), 'html.parser')

for tag in soup.find_all('p', {"class": "fnp2"}) :
    line = unicode(str(tag).split(':')[0], "utf-8")
    line = re.sub('(<p class="fnp2">)(\d+) ', '', line)
    line = line.replace('„', '')
    print line

但为此,我总是收到UnicodeDecodeError

line = line.replace('„', '')

UnicodeDecodeError: 'ascii' codec can't decode byte 0x84 in position
0: ordinal not in range(128)

对此有什么解决方案?

【问题讨论】:

  • 您的 .xhtml 是否指定了编码?
  • 尝试将有问题的行更改为 line.replace(u'„', '')。但是,您也可能在“打印”语句中遇到错误。最后,确保您的脚本文件实际上保存在 cp1252 中(或者更好的是,始终对所有代码使用 UTF8,并将其标记在标题中)。
  • 你试过open("file.xhtml", encoding='utf-8')吗?
  • @lit 是的:&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"&gt;
  • @KT。谢谢你。似乎line.replace(u'„', '') 是答案。除了在文件开头写# -*- coding: cp1252 -*-之外,如何确保脚本文件保存在cp1252中? @lit 和 @TigerhawkT3 谢谢你的建议。

标签: python python-2.7 beautifulsoup


【解决方案1】:

代码中的line 变量是unicode 对象。当您调用line.replace 时,Python 期望第一个参数也是unicode 对象。如果您改为提供str 对象,Python 将尝试使用系统默认编码(您可以通过sys.getdefaultencoding() 检查)自动将其解码为unicode 字符串。

显然,在您的情况下,系统编码是ascii。使用ascii 编解码器无法解码字节字符串'„',因为'„' 不是ACII 符号,这会导致您看到的异常。

您可以通过 changing the default system encoding 将问题修复为您用于提供 '„' 字符串(我猜是 CP1252)的同一个问题,但是这样的修复仅从学术角度来看很有趣,因为它只是扫荡地毯下的问题。

对您的问题的正确、安全和简单的解决方法是首先简单地为replace 方法提供一个unicode 对象。这就像在您的代码中将 '„' 替换为 u'„' 一样简单。

【讨论】:

    猜你喜欢
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多