“笨方法”學Python(第三版)ex41 學習面向物件術語 Python 3.6.5程式碼
阿新 • • 發佈:2019-02-04
新手一枚,買的書是教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 %%%.", "***.***(@@@)": "From *** get the *** function, and call it with parameters self, @@@.", "***.*** = '***'": "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 word from the website for word in urlopen(WORD_URL).readlines(): word = word.decode() #bytes變為str 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 name for word in class_names: result = result.replace("%%%", word, 1) # fake other name for word in other_names: result = result.replace("***", word, 1) # fake parameter name 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: %s\n\n" % answer) except EOFError: print("\nBye")
新手一枚,暫時做了這些,歡迎指正和交流