如何从苦学python中阅读习题41的代码? [英] How to read the code of exercise 41 from learn python the hard way?
问题描述
我正在尝试理解以下代码,但遇到了困难.有人可以通过回答几个问题来帮助我理解吗?
我知道 PHRASES(一个变量)包含一个字典,所以class %%%(%%%)"映射到创建一个名为 %%% 的类,即-a %%%."
这些行(第 2-13 行)实际上也创建了类还是它们就像字符串"一样?因为看起来它可能正在创建类,但我不确定.
我也知道 %%%、* 和 @@@ 实际上会被代码中某处的实际单词替换,但不知道如何或在哪里,因为看起来都是这样令人困惑.
那么,有人可以帮我吗?谢谢!
1 PHRASES = {2类%%%(%%%):":3 "创建一个名为 %%% 的类,即-a %%%.",4 "class %%%(object):\n\tdef __init__(self, ***)" :5 "class %%% has-a __init__ 接受 self 和 *** 参数.",6 "类 %%%(对象):\n\tdef ***(self,@@@)":7 "类 %%% 有一个名为 *** 的函数,它接受 self 和 @@@ 参数.",8 "*** = %%%()":9 "将 *** 设置为类 %%% 的实例.",10"***.***(@@@)":11 "从***获取***函数,并带参数self,@@@调用它.",12 "***.*** = '***'":13从***获取***属性并将其设置为'***'."14 }
哦,这里是完整的代码,以备不时之需:
随机导入从 urllib 导入 urlopen导入系统WORD_URL = "http://learncodethehardway.org/words.txt"单词 = []短语 = {班级 %%%(%%%):":"创建一个名为 %%% 的类,即-a %%%.","class %%%(object):\n\tdef __init__(self, ***)" :"class %%% has-a __init__ 接受 self 和 *** 参数.",类 %%%(对象):\n\tdef ***(自我,@@@)":"class %%% 有一个名为 *** 的函数,它接受 self 和 @@@ 参数.",*** = %%%()":"将 *** 设置为 %%% 类的实例.","***.***(@@@)":"从***获取***函数,并以参数self、@@@调用.",***.*** = '***'":从***获取***属性并将其设置为'***'."}PHRASE_FIRST = 错误如果 len(sys.argv) == 2 和 sys.argv[1] == "english":PHRASE_FIRST = 真对于 urlopen(WORD_URL).readlines() 中的单词:WORDS.append(word.strip())def 转换(片段,短语):class_names = [w.capitalize() for w inrandom.sample(WORDS,snippet.count("%%%"))]other_names = random.sample(WORDS, snippet.count("***"))结果 = []param_names = []对于 i 在范围内(0,snippet.count(@@@")):param_count = random.randint(1,3)param_names.append(', '.join(random.sample(WORDS, param_count)))对于片段中的句子,短语:结果 = 句子[:]对于 class_names 中的单词:result = result.replace("%%%", word, 1)对于 other_names 中的单词:result = result.replace("***", word, 1)对于 param_names 中的单词:result = result.replace("@@@", word, 1)结果.附加(结果)返回结果尝试:为真:片段 = PHRASES.keys()random.shuffle(片段)对于片段中的片段:短语 = 短语 [片段]问题,答案 = 转换(片段,短语)如果 PHRASE_FIRST:问题,答案 = 答案,问题打印问题原始输入(>")打印 "ANSWER: %s\n\n" % answer除了EOFError:打印\n再见"
这些行正在创建一个字符串字典,其中的键具有与有效 Python 类定义相似的语法和描述它们正在做什么的值.
例如,"class %%%(object):\n\tdef __init__(self, ***)"
成为
class %%%(object):def __init__(self, ***)
<块引用>
我也知道 %%%
、***
和 @@@
实际上会被替换为代码,但不知道如何或在哪里,因为它看起来很混乱.
这一点很明显,例如:
result = result.replace("@@@", word, 1)
单词取自 WORD_URL = "http://learncodethehardway.org/words.txt"
.
I'm trying to understand the following code and am having a difficult time of it. Can someone help me to understand by answering a couple of questions?
I know that PHRASES (a variable) contains a dictionary, so "class %%%(%%%)" maps to "Make a class named %%% that is-a %%%."
Are the lines (line 2-13) also actually create classes or are they just like "strings"? Because it looks like it might be creating classes, but I'm not sure.
I also know that %%%, *, and @@@ will actually get replaced by actual words somewhere in the code, but don't know how or where because it just all looks so confusing.
So, can anyone help me? Thanks!
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 }
Oh, and here's the entire code in case you need it:
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"
The lines are creating a dictionary of strings with keys that have similar syntax to a valid Python class definition and values that describe what they are doing.
For example, "class %%%(object):\n\tdef __init__(self, ***)"
Becomes
class %%%(object):
def __init__(self, ***)
I also know that
%%%
,***
, and@@@
will actually get replaced by actual words somewhere in the code, but don't know how or where because it just all looks so confusing.
This bit is pretty obvious, e.g.:
result = result.replace("@@@", word, 1)
The words are fetched from WORD_URL = "http://learncodethehardway.org/words.txt"
.
这篇关于如何从苦学python中阅读习题41的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!