当前位置: 首页 > 面试题库 >

Python3错误:TypeError:无法将“字节”对象隐式转换为str

梁丘宏硕
2023-03-14
问题内容

我正在学习pythonthehardway中进行练习41,并不断收到错误:

  Traceback (most recent call last):
  File ".\url.py", line 72, in <module>
    question, answer = convert(snippet, phrase)
  File ".\url.py", line 50, in convert
    result = result.replace("###", word, 1)
TypeError: Can't convert 'bytes' object to str implicitly

我使用的是python3,而书籍使用的是python2,因此我进行了一些更改。这是脚本:

#!/usr/bin/python
# Filename: urllib.py

import random
from random import shuffle
from urllib.request import urlopen
import sys

WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []

PHRASES = {
            "class ###(###):":
                "Make a class named ### that is-a ###.",
            "class ###(object):\n\tdef __init__(self, ***)" :
                "class ### has-a __init__ that takes self and *** parameters.",
            "class ###(object):\n\tdef ***(self, @@@)":
                "class ### has-a funciton named *** that takes self and @@@ parameters.",
            "*** = ###()":
                "Set *** to an instance of class ###.",
            "***.*** = '***'":
                "From *** get the *** attribute and set it to '***'."
}

# do they want to drill phrases first
PHRASE_FIRST = False
if len(sys.argv) == 2 and sys.argv[1] == "english":
    PHRASE_FIRST = True

# load up the words from the website
for word in urlopen(WORD_URL).readlines():
    WORDS.append(word.strip())

def convert(snippet, phrase):
    class_names = [w.capitalize() for w in
                    random.sample(WORDS, snippet.count("###"))]
    other_names = random.sample(WORDS, snippet.count("***"))
    results = []
    param_names = []

    for i in range(0, snippet.count("@@@")):
        param_count = random.randint(1,3)
        param_names.append(', '.join(random.sample(WORDS, param_count)))

    for sentence in snippet, phrase:
        result = sentence[:]

        # fake class names
        for word in class_names:
            result = result.replace("###", word, 1)

        # fake other names
        for word in other_names:
            result = result.replace("***", word, 1)

        # fake parameter lists
        for word in param_names:
            result = result.replace("@@@", word, 1)

        results.append(result)

    return results

# keep going until they hit CTRL-D
try:
    while True:
        snippets = list(PHRASES.keys())
        random.shuffle(snippets)

        for snippet in snippets:
            phrase = PHRASES[snippet]
            question, answer = convert(snippet, phrase)
            if PHRASE_FIRST:
                question, answer = answer, question

            print(question)

            input("> ")
            print("ANSWER: {}\n\n".format(answer))
except EOFError:
    print("\nBye")

我到底在做什么错?谢谢!


问题答案:

urlopen()返回一个bytes对象,要对其执行字符串操作,应将其转换为strfirst。

for word in urlopen(WORD_URL).readlines():
    WORDS.append(word.strip().decode('utf-8')) # utf-8 works in your case


 类似资料:
  • 问题内容: 我正在尝试编写文本游戏,但在定义的函数中遇到了错误,该错误使你基本上无法在制作角色后花费技能点。最初,错误表明我正在尝试从代码的这一部分的整数中减去一个字符串。显然这是错误的,所以我用… 修复了它,但是现在我遇到了一个以前从未见过的错误(新程序员),并且我对确切要告诉我的内容以及如何解决它感到困惑。 这是我的部分功能不起作用的代码: 这是我在shell中获得这部分代码时遇到的错误: 有

  • 问题内容: 我正在尝试测试某个数字的十进制表示形式是否至少包含两次数字9,所以我决定执行以下操作: 但是Python始终会以“ TypeError:无法将’int’对象隐式转换为str”进行响应。 我在这里做错了什么?实际上,是否存在一种更聪明的方法来检测整数的十进制表示形式中包含某个数字的频率? 问题答案: 您的问题在这里: 您需要使字符串文字,而不是整数: 为了更好地计算字符串中出现的次数,请

  • 我试图通过API发送数据,但得到了类型错误:无法将字节转换为str。我理解这意味着我需要将部分代码转换为字节,但我不确定如何执行。我尝试在前面添加b或使用字节(“数据”),但可能将它们放在了错误的区域。 这是问题行: 我不确定什么和如何转换为字节。

  • 我试图检查是否为。但我得到了一个错误: 无法将null转换为对象 我该如何进行? 我正在检查组和用户是否存在,否则将添加它们。

  • 问题内容: 我将开始处理需要读取字节并创建字符串的内容。读取的字节代表UTF-16字符串。因此,为了进行测试,我想将UTF-16编码的简单字节数组转换为字符串。数组中的前2个字节必须表示字节序,因此必须为0xff 0xfe或0xfe 0xff。所以我尝试如下创建字节数组: 但是我收到一个错误,因为0xFF和0xFE太大而无法容纳一个字节(因为字节是用Java签名的)。更准确地说,错误是int无法转

  • 问题内容: 如果我在运行时有一个Class实例,是否可以获取其byte []表示形式?我感兴趣的字节将为Class文件格式,这样它们将是[ClassLoader.defineClass] [3]的有效输入。 [3]:http : //java.sun.com/j2se/1.5.0/docs/api/java/lang/ClassLoader.html#defineClass(java.lang.S