标签:readlines init name str return efi out dom sed
一 词汇训练
二 短语训练
三 代码
1 相关知识
2 代码
1 import random 2 from urllib.request import urlopen 3 import sys 4 5 WORD_URL = "http://learncodethehardway.org/words.txt" 6 WORDS = [] 7 8 PHRASES = { 9 "class %%%(%%%):": 10 "Make a class named %%% that is-a %%%.", 11 "class %%%(object):\n\tdef __init__(self,***)": 12 "class %%% has-a __init__ that takes self and *** params.", 13 "class %%%(object):\n\tdef ***(self,@@@)": 14 "class %%% has-a function *** that takes self and @@@ params.", 15 "*** = %%%()": 16 "Set *** to an instance of class %%%.", 17 "***.***(@@@)": 18 "From *** get the *** function,call it with params self @@@.", 19 "***.*** = ‘***‘": 20 "From *** get the *** attribute and set it to ‘***‘." 21 } 22 23 # do they want to drill phrases first 24 if len(sys.argv) == 2 and sys.argv[1] == "english": 25 PHRASE_FIRST = True 26 else: 27 PHRASE_FIRST = False 28 29 # load up the words from the website 30 for word in urlopen(WORD_URL).readlines(): 31 WORDS.append(str(word.strip(),encoding="utf-8")) 32 33 def convert(snippet,phrase): 34 class_names = [w.capitalize() for w in 35 random.sample(WORDS,snippet.count("%%%"))] 36 other_names = random.sample(WORDS,snippet.count("***")) 37 results = [] 38 param_names = [] 39 40 for i in range(0,snippet.count("@@@")): 41 param_count = random.randint(1,3) 42 para_names.append(‘,‘.join( 43 random.sample(WORDS,param_count))) 44 45 for sentence in snippet,phrase: 46 result = sentence[:] 47 48 # fake class names 49 for word in class_names: 50 result = result.replace("%%%",word,1) 51 52 # fake other names 53 for word in other_names: 54 result = result.replace("***",word,1) 55 56 # fake parameter lists 57 for word in param_names: 58 result = result.replace("@@@",word,1) 59 60 results.append(result) 61 return results 62 63 # keep going until they hit CTRL-D 64 try: 65 while True: 66 snippets = list(PHRASES.keys()) 67 random.shuffle(snippets) 68 69 for snippet in snippets: 70 phrase = PHRASES[snippet] 71 question,answer = convert(snippet,phrase) 72 if PHRASE_FIRST: 73 question,answer = answer,question 74 75 print(question) 76 77 input("> ") 78 print(f"ANSWER:{answer}\n\n") 79 except EOFError: 80 print("\nBye")
标签:readlines init name str return efi out dom sed
原文地址:https://www.cnblogs.com/luoxun/p/13399256.html