问题描述
我正在 learnpythonthehardway 中的练习 41 并不断收到错误:
i am working on exercise 41 in learnpythonthehardway and keep getting the error:
traceback (most recent call last): file ".url.py", line 72, inquestion, 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,所以我做了一些更改.这是脚本:
i am using python3 while the books uses python2, so i have made some changes. here is the script:
#!/usr/bin/python # filename: urllib.py import random from random import shuffle from urllib.request import urlopen import sys word_url = "http://www.51sjk.com/upload/articles/1/0/340/340399_20221223101818247.txt" words = [] phrases = { "class ###(###):": "make a class named ### that is-a ###.", "class ###(object): def __init__(self, ***)" : "class ### has-a __init__ that takes self and *** parameters.", "class ###(object): def ***(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: {} ".format(answer)) except eoferror: print(" bye")
我到底做错了什么?谢谢!
what exactly am i doing wrong here? thanks!
推荐答案
urlopen() 返回一个字节对象,要对其执行字符串操作,您应该将其转换为 str 首先.
urlopen() returns a bytes object, to perform string operations over it you should convert it to str first.
for word in urlopen(word_url).readlines(): words.append(word.strip().decode('utf-8')) # utf-8 works in your case
要获得正确的字符集:如何下载python中有正确字符集的任何(!)网页吗?