【问题标题】:String object has no attribute 'decode' when converting UTF-8转换 UTF-8 时字符串对象没有属性“解码”
【发布时间】:2023-03-16 12:36:01
【问题描述】:

我正在尝试将G\xc3\xb6del 转换为Gödel(具体而言,将\xc3\xb6d 转换为ö),但我找不到执行此操作的方法。当我运行以下代码时,我收到一个错误:

>>> string = '\xc3\xb6'
>>> string.decode(encoding='UTF-8') 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'decode'

This question 似乎没有帮助,任何其他看起来相似的人也没有帮助,因为它们都来自2.x。一位朋友提到了 base 64 编码,但我不确定这有什么帮助。我似乎无法在3.8 中找到我应该做的转换,那么最好的方法是什么?

【问题讨论】:

  • 你是怎么得到那个字符串的?在某个时候它可能是一个字节对象吗? b'G\xc3\xb6del'.decode('utf-8') --> 'Gödel'
  • @UlasKeles 它确实是一个字节对象。我从网页中提取了它,确切地说是 SCP 基金会,并想用我的 Discord 机器人在消息中发送它。我已经找到了该问题的解决方案,我将在几分钟内发布答案。

标签: python python-3.x string utf-8 character-encoding


【解决方案1】:

这里的问题是字符串已经被解码。基本上你encode一个字符串对象到一个字节对象,逆操作是decoding一个字节对象到一个字符串对象。这就是字符串没有属性decode 的原因。可以这样想:

String -> encode -> Byte
Byte -> decode -> String

在这种情况下,解决方案是调用 encode 方法并传入 'utf8''ascii',具体取决于上下文和情况。

然而, 这不仅仅是将它转换为字符串对象,这里就是这种情况。作为这个问题的 OA,我确实知道这是什么意思,以及我是如何找到解决方案的。 Gödel 的值是通过抓取 SCP 基金会页面,找到项目等级然后传递给我的 Discord 机器人以获取命令而获得的。这是我的代码:

link = f"http://www.scp-wiki.net/scp-{num}"
page = get(link)

obj_class = [str(i) for i in page.iter_lines() if b"Object Class:" in i][0]
# ^ There should only be one line in the document matching that requirement.
# The type of this line is a byte object, which is why conversion is necessary later on.
obj_class = re.findall('(?<=\<\/strong> )(.*?)(?=\<)', obj_class)[0]
# ^ Find the actual class in that line.
print(obj_class)  # expected Gödel, got G\xc3\xb6del instead.

上面不会引发异常,它只是不会根据需要转换字符编码。一旦我了解发生了什么,我的解决方法很简单;将str(i) 替换为i.decode('utf8')

obj_class = [i.decode('utf8') for i in page.iter_lines() if b"Object Class:" in i][0]
# ^ decoding it there really makes the difference, converting it to utf-8 without dealing with
# the issues of decoded strings later on.

这将返回所需的值Gödel,而不是G\xc3\xb6del。我希望这个对你有用。如果我犯了任何错误,请告诉我,以便我进行必要的更正。

【讨论】:

    猜你喜欢
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 2012-05-29
    • 1970-01-01
    相关资源
    最近更新 更多