我试图理解下面的代码,并且遇到了困难。有人可以回答几个问题来帮助我理解吗?
我知道PHRASES(变量)包含字典,因此“类%%%(%%%)”映射为“使名为%%%的类为-a %%%”。
这些行(第2-13行)是否也实际上是在创建类,还是就像“字符串”一样?因为它看起来可能正在创建类,但是我不确定。
我也知道%%%, * 和@@@实际上会被代码中某些地方的实际单词替换,但是不知道如何或在哪里,因为它们看上去都如此令人困惑。
那么,有人可以帮助我吗?谢谢!
1 PHRASES = { 2 "class %%%(%%%):": 3 "Make a class named %%% that is-a %%%.", 4 "class %%%(object):\n\tdef __init__(self, ***)" : 5 "class %%% has-a __init__ that takes self and *** parameters.", 6 "class %%%(object):\n\tdef ***(self, @@@)": 7 "class %%% has-a function named *** that takes self and @@@ parameters.", 8 "*** = %%%()": 9 "Set *** to an instance of class %%%.", 10 "***.***(@@@)": 11 "From *** get the *** function, and call it with parameters self, @@@.", 12 "***.*** = '***'": 13 "From *** get the *** attribute and set it to '***'." 14 }
哦,这是您需要时的全部代码:
import random from urllib import urlopen 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 '***'." } PHRASE_FIRST = False if len(sys.argv) == 2 and sys.argv[1] == "english": PHRASE_FIRST = True 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[:] for word in class_names: result = result.replace("%%%", word, 1) for word in other_names: result = result.replace("***", word, 1) for word in param_names: result = result.replace("@@@", word, 1) results.append(result) return results try: while True: snippets = 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 raw_input("> ") print "ANSWER: %s\n\n" % answer except EOFError: print "\nBye"
这些行正在创建一个字符串字典,这些字典的键的语法与有效的Python类定义相似,而值则描述它们的作用。
例如, "class %%%(object):\n\tdef __init__(self, ***)"
"class %%%(object):\n\tdef __init__(self, ***)"
成为
class %%%(object): def __init__(self, ***)
我也知道%%%,***和@@@真正能拿到的实际词语的代码替换某个地方,但不知道如何或在哪里,因为它只是一切看起来如此混乱。
%%%
***
@@@
这一点很明显,例如:
result = result.replace("@@@", word, 1)
这些单词是从中获取的WORD_URL = "http://learncodethehardway.org/words.txt"。
WORD_URL = "http://learncodethehardway.org/words.txt"