我被这个练习的另一部分卡住了。正在编码的程序允许你钻取短语(它给你一段代码,你写出英文翻译),我对"convert"函数的工作原理感到困惑。完整代码:http://learnpythonthehardway.org/book/ex41.html
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[:]
# 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
我很失落。w.capitalize()
中的"w"是文件本身,还是只是指列表中的对象?我也不确定为什么.count()
函数会出现在.sample()
的参数中(或者.sample()
的实际作用)。第一个for_loop的目的是什么?
谢谢你的帮助,我对接二连三的问题感到抱歉。
如果它能帮助你,
class_names = [w.capitalize() for w in
random.sample(WORDS, snippet.count("%%%"))]
相当于
class_names = []
for w in random.sample(WORDS, snippet.count("%%%")):
class_names.append(w.capitalize())
.count()将返回代码段字符串中"%%%"的出现次数,因此random.sample将从WORDS列表中选择N个元素的子集,其中N是代码段字符串"%%%"的元素。
w.capitalize()
类似于.uppercase()
,但它只为第一个字符加上字幕。