新手一枚,买的书是教Python2,想学Python3,ex41一直报错,上网查后发现主要是三个问题:
1. Python3中urllib库发生变化
2. Python3中严格区分str和bytes,29行遍及读取网页上的单词,word为bytes,不能作为replace()的第二个参数
3. Python3中dict.keys返回的不是列表,需要用list()处理
下面贴出可以python3.6.5可以运行的代码:
import random
from urllib.request import urlopen #改成python3中的方法
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 function named *** that takes self and @@@ parameters.",
"*** = %%%()":
"Set *** to an instance of class %%%.",