标签: Python 博客
博主最近在学习Python,看的书是Learn Python The Hard Way(Third Edition), 前40道习题没有什么难度,但是看到习题41的时候,由于出现了很多新函数和新名字以及印刷错误,竟然没看懂这道题的目的。查询了一些函数的用法之后,现在把这道题搞清楚了,分享出来,希望能对其他新手有所帮助。
译者:王巍巍
版次:2014年11月第1版
印刷时间:2015年5月北京第3次印刷
具体错误:
#fake class namesfor word in class_names: result = result.replace('%%%', word, 1)# fake other namesfor word in other_names: result = result.replace('***', word, 1)# fake parameter listsfor word in param_names: result = result.replace('@@@', word, 1)results.append(result)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
上面的一段代码在书中是Line47~Line59,这一段代码应该全部再缩进一格,即这段代码处于for sentence in snippet, phrase:
的循环中,具体可以参考Exercise 41: Learning To Speak Object Oriented
首次出现位置:Line30
函数原型:str.strip([chars])
参数:chars – 移除字符串头尾指定的字符,默认为空格
返回值:返回移除字符串头尾指定的字符生成的新字符串,移除的是chars中的任意字符
实例:
>>> a = ' 123'>>> print a.strip()123>>> a ='123abc'>>>print a.strip('1cb')23a
首次出现位置:Line34
函数原型:str.capitalize()
参数:None
返回值:返回一个首字母大写,其余字母小写的字符串
实例:
>>> a = 'this is a book called HARRY POTTER'>>> print a.capitalize()This is a book called harry potter
首次出现位置:Line35
函数原型:random.sample(sequence, k)
参数:sequence是一个list,k是一个整数
返回值:返回一个list,该list由sequence中随机的k个元素组成,sequence不变
实例:
>>>list = [1,2,3,4,5,6,7,8,9,10]>>>slice = random.sample(list,5)>>>print slice[3,6,8,2,4]#截取的序列元素并没有顺序
首次出现位置:Line35
函数原型:str.count(sub, start= 0,end=len(str))
参数:
返回值:返回子字符串在字符串中出现的次数
实例:
>>>a = 'this is a book called HARRY POTTER'>>>print a.count('i')2
首次出现位置:Line42
函数原型:str.join(sequence)
参数:sequence – 要连接元素的list
返回值:返回通过str连接序列中元素后生成的字符串
实例:
>>>str = '-'>>>seq = ['a','b','c']>>>print str.join(seq)a-b-c
首次出现位置:Line49
函数原型:str.replace(old, new[, max])
参数:
返回值:返回以new代替old不超过max次的新字符串
实例:
>>>a = 'this is a book called HARRY POTTER'>>>print a.replace('is', 'was', 1)thwas is a book called HARRY POTTER>>>print a.replace('is', 'was')thwas was a book called HARRY POTTER
首次出现位置:Line67
函数原型:dict.keys()
参数:None
返回值:返回一个字典所有的键
实例:
>>>dict = {'name':'moverzp', 'age':'23', 'height':'180'}>>>print dict.keys()['age','name','height']
首次出现位置:Line68
函数原型:random.shuffle(lst)
参数:lst – 可以是一个序列或者元组
返回值:None. 直接修改lst的顺序
实例:
>>>list = [1, 2, 3, 4]>>>random.shuffle(list)>>>print list[3, 1, 4, 2]>>>random.shuffle(list)>>>print list[1, 4, 2, 3]
这段脚本的作用其实就是在设定网页中随机取出单词当做类的名字,函数的名字或者参数的名字。具体操作就是把PHRASES中的”%%%”,”***”,”@@@”替换成随机选择的单词而已,PHRASE_FIRST决定先打印单词替换符号后key-value(键值对)中的key还是value。
分别以流程图和代码注释说明。
import randomfrom urllib import urlopenimport sysWORD_URL = 'http://learncodethehardway.org/words.txt'#该网页中全是单独成行的单词WORDS = []PHRASES = { #编写脚本时应该写的代码为key,其解释为value '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 '***'.'}# do they want to drill phrases firstPHRASE_FIRST = False #False表示先打印key,按下任意键后再打印valueif len(sys.argv) == 2 and sys.argv[1] == 'english': PHRASE_FIRST = True #True表示先打印value,按下任意键后再打印key# load up the words from the websitefor word in urlopen(WORD_URL).readlines(): #一行一行从网页中读取数据 WORDS.append(word.strip()) #删除每一行开始和结尾的空格,只留下单词并加入到words列表中#先从下面的try开始看,调用到该函数时再看回来def convert(snippet, phrase): #我们以传入的具体参数来分析 class_names = [w.capitalize() for w in #从WORDS序列中随机取出1个单词首字母大写后赋值给class_names,此处假设为'Actor' random.sample(WORDS, snippet.count('%%%'))] other_names = random.sample(WORDS, snippet.count('***')) #从WORDS序列中随机取出一个单词赋值给other_names,此处假设为'dinner' results = [] param_names = [] for i in range(0, snippet.count('@@@')): #只循环一次 param_count = random.randint(1,3) #假设随机到了2 param_names.append(', '.join(random.sample(WORDS, param_count))) #从WORDS中随机取出2个单词用逗号和空格连接起来,放在param_names中,假设为'cook, donkey' for sentence in snippet, phrase: #循环两次,只讲解第一次循环 result = sentence[:] #深拷贝,result = 'class %%%(object):\n\tdef ***(self, @@@)' # fake class names for word in class_names: result = result.replace('%%%', word, 1) #result = 'class Actor(object):\n\tdef ***(self, @@@)' # fake other names for word in other_names: result = result.replace('***', word, 1) #result = 'class Actor(object):\n\tdef dinner(self, @@@)' # fake parameter lists for word in param_names: result = result.replace('@@@', word, 1) #result = 'class Actor(object):\n\tdef dinner(self, cook, donkey)' results.append(result) #添加到results序列中 return results #results = ['class Actor(object):\n\tdef dinner(self, cook, donkey)', 'class Actor has-a function named dinner that takes self and cook, donkey parameters.']# keep going until they hit CTRL-Dtry: while True: snippets = PHRASES.keys() #提取PHRASES中的键 random.shuffle(snippets) #打乱snippets中元素(PHRASES中键)顺序 for snippet in snippets: #取一个键来操作,假设取到'class %%%(object):\n\tdef ***(self, @@@)' phrase = PHRASES[snippet] #取出值'class %%% has-a function named *** that takes self and @@@ parameters.' question, answer = convert(snippet, phrase) #现在去上面看这个函数的定义 if PHRASE_FIRST: #先打印value,再打印key question, answer = answer, question print question raw_input('> ') print 'ANSWER: %s\n\n' % answerexcept EOFError: print '\nBye'
联系客服