Python Help - Learn Python The Hard Way exercise 41 "phrase = PHRASES[snippet]" -
i learning python - first programming language learning. little confused 1 line of code. full code can found @ http://learnpythonthehardway.org/book/ex41.html
import random urllib import urlopen import sys word_url = "http://learncodethehardway.org/words.txt" words = [] phrases = { "class %%%(%%%):": "make class named %%% is-a %%%.", "class %%%(object):\n\tdef __init__(self, ***)" : "class %%% has-a __init__ takes self , *** parameters.", "class %%%(object):\n\tdef ***(self, @@@)": "class %%% has-a function named *** takes self , @@@ parameters.", "*** = %%%()": "set *** instance of class %%%.", "***.***(@@@)": "from *** *** function, , call parameters self, @@@.", "***.*** = '***'": "from *** *** attribute , set '***'." } # want drill phrases first phrase_first = false if len(sys.argv) == 2 , sys.argv[1] == "english": phrase_first = true # load words website word in urlopen(word_url).readlines(): words.append(word.strip()) def convert(snippet, phrase): class_names = [w.capitalize() w in random.sample(words, snippet.count("%%%"))] other_names = random.sample(words, snippet.count("***")) results = [] param_names = [] in range (0, snippet.count("@@@")): param_count = random.randint(1,3) param_names.append(', '.join(random.sample(words, param_count))) sentence in snippet, phrase: result = sentence[:] # fake class name word in class_names: result = result.replace("***", word, 1) # fake other names word in other_names: result = result.replace("***", word, 1) # fake parameter lists word in param_names: result = result.replace("@@@", word, 1) results.append(result) return results # keep going until hit ctrl-d try: while true: snippets = phrases.keys() # returns randomly shuffled dictionary keys list random.shuffle(snippets) snippet in snippets: phrase = phrases[snippet] question, answer = convert(snippet, phrase) if phrase_first: question, answer = answer, question print question raw_input("> ") print "answer: %s\n\n" % answer except eoferror: print "\nbye"
it 11th line of code bottom don't quite understand: phrase = phrases[snippet]
. since snippet in for snippet in snippets:
looping through keys of randomized-shuffled phrases list, why can't code phrase = snippet
. in advance help. cheers - darren
Comments
Post a Comment