import random
from urllib.request import urlopen
import sys
WORD_URL = "http://learncodethehardway.org/words.txt"
WORDS = []
PHRASES = {
"class %%%(%%%):":
# 创建一个叫X的类。它是Y的一种
"Make a class named %%% that is-a %%%.",
"class %%%(object):\n\tdef __init__(self, ***)":
"class %%% has-a __init__ that takes self and *** params.",
# 类X有一个__init__函数,它接受(self)和(J)为参数
"class %%%(object):\n\tdef ***(self, @@@)":
"class %%% has-a function *** that takes self and @@@ params.",
# 类X有一个名为M的函数,它接收self和J为参数
"*** = %%%()":
"Set *** to an instance of class %%%.",
# 将foo设为类X的一个实例
"***.***(@@@)":
"From *** get the *** function, call it with params self, @@@.",
# 从foo中找到函数m,并使用self和J参数调用它
"***.*** = '***'":
"From *** get the *** attribute and set it to '***'."
# 从foo中获取K属性,并将其设为Q
}
# do they want to drill pharases first
if len (sys.argv) == 2 and sys.argv[1] == "english":
#
PHRASE_FIRST = True
else:
PHRASE_FIRST = False
# load up the words from the website
# 从网页中下载文字
for word in urlopen(WORD_URL).readlines():
WORDS.append(str(word.strip(), encoding="utf-8"))
def convert(snippet, phrase):
class_names = [w.capitalize() for w in
random.sample(WORDS, snippet.count("%%%"))]
# 从words序列中抽取带'###'的字符串,数量是片段里面含有'###'的数量并把第一个字母变大写,后面变小些(也就是随机抽取类)
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 names
for word in class_names:
result = result.replace("%%%", word, 1)
# fake other names
for word in other_names:
result = result.replace("***", word, 1)
# fake parameter lists
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(f"ANSWER: {answer}\n\n")
except EOFError:
print("\nBye")
看不懂,日后再看,,