[关闭]
@jtahstu 2018-01-12T10:12:16.000000Z 字数 18081 阅读 6591

Python语言及其应用练习解答

python


第一章

1.9 练习
本章介绍了Python 语言——它是干什么的、它是什么样的以及它在计算机世界中的作
用。在每章的结尾我都会列出一些小练习来帮助你巩固刚学到的知识并为学习新知识做
好准备。
(1) 如果你还没有安装Python 3,现在就立刻动手。具体方法请阅读附录D。
(2) 启动Python 3 交互式解释器。再说一次,具体方法请阅读附录D。它会打印出几行信息
和一行>>>,这是你输入Python 命令的提示符。
(3) 随便玩玩解释器。可以用它来计算8 * 9,按下回车来查看结果,Python 应该会打印出
72。
(4) 输入数字47 并按下回车,解释器有没有在下一行打印出47 ?
(5) 现在,输入print(47) 并按下回车,解释器有没有在下一行打印出47 ?

  1. ~ python3
  2. Python 3.6.3 (v3.6.3:2c5fed86e0, Oct 3 2017, 00:32:08)
  3. [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
  4. Type "help", "copyright", "credits" or "license" for more information.
  5. >>> 8*9
  6. 72
  7. >>> 47
  8. 47
  9. >>> print(47)
  10. 47

第二章

2.4 练习
本章介绍了Python 最基本的元素:数字、字符串以及变量。我们试着在交互式解释器里完
成一些相关的练习。
(1) 一个小时有多少秒?这里,请把交互式解释器当作计算器使用,将每分钟的秒数(60)
乘以每小时的分钟数(60)得到结果。
(2) 将上一个练习得到的结果(每小时的秒数)赋值给名为seconds_per_hour 的变量。
(3) 一天有多少秒?用你的seconds_per_hour 变量进行计算。
(4) 再次计算每天的秒数,但这一次将结果存储在名为seconds_per_day 的变量中。
(5) 用seconds_per_day 除以seconds_per_hour,使用浮点除法(/)。
(6) 用seconds_per_day 除以seconds_per_hour,使用整数除法(//)。除了末尾的.0,本
练习所得结果是否与前一个练习用浮点数除法得到的结果一致?

  1. >>> seconds_per_hour = 60 * 60
  2. >>> seconds_per_day = seconds_per_hour * 24
  3. >>> seconds_per_day / seconds_per_hour
  4. 24.0
  5. >>> seconds_per_day // seconds_per_hour
  6. 24

第三章

3.8 练习
在这一章,你见到了一些更为复杂的数据结构:列表、元组、字典和集合。你可以使用
这些数据结构以及第2 章提到的数据类型(数字和字符串)来表示现实生活中各种各样
的元素。
(1) 创建一个叫作years_list 的列表,存储从你出生的那一年到五岁那一年的年份。例
如,如果你是1980 年出生的,那么你的列表应该是years_list = [1980, 1981, 1982,
1983, 1984, 1985]。
如果你现在还没到五岁却在阅读本书,那我真的没有什么可教你的了。
(2) 在years_list 中,哪一年是你三岁生日那年?别忘了,你出生的第一年算0 岁。
(3) 在years_list 中,哪一年你的年纪最大?
(4) 创建一个名为things 的列表, 包含以下三个元素:"mozzarella"、"cinderella" 和
"salmonella"。
(5) 将things 中代表人名的字符串变成首字母大写形式,并打印整个列表。看看列表中的
元素改变了吗?
(6) 将things 中代表奶酪的元素全部改成大写,并打印整个列表。
(7) 将代表疾病的元素从things 中删除,收好你得到的诺贝尔奖,并打印列表。
(8) 创建一个名为surprise 的列表,包含以下三个元素:"Groucho"、"Chico" 和"Harpo"。
(9) 将surprise 列表的最后一个元素变成小写,翻转过来,再将首字母变成大写。
(10) 创建一个名为e2f 的英法字典并打印出来。这里提供一些单词对:dog 是chien,cat
是chat,walrus 是morse。
(11) 使用你的仅包含三个词的字典e2f 查询并打印出walrus 对应的的法语词。
(12) 利用e2f 创建一个名为f2e 的法英字典。注意要使用items 方法。
(13) 使用f2e,查询并打印法语词chien 对应的英文词。
(14) 创建并打印由e2f 的键组成的英语单词集合。
(15) 建立一个名为life 的多级字典。将下面这些字符串作为顶级键:'animals'、'plants'
以及'others'。令'animals' 键指向另一个字典,这个字典包含键'cats'、'octopi'
以及'emus'。令'cat' 键指向一个字符串列表,这个列表包括'Henri'、'Grumpy' 和
'Lucy'。让其余的键都指向空字典。
(16) 打印life 的顶级键。
(17) 打印life['animals'] 的全部键。
(18) 打印life['animals']['cats'] 的值。

  1. """
  2. @author: jtahstu
  3. @contact: root@jtahstu.com
  4. @site: http://www.jtahstu.com
  5. @time: 2018/1/9 14:39
  6. """
  7. # 1
  8. years_list = [1980, 1981, 1982, 1983, 1984, 1985]
  9. # 2
  10. print(years_list[3]) # 1983
  11. # 3
  12. print(years_list[-1]) # 1985
  13. # 4
  14. things = ['mozzarella', 'cinderella', 'salmonella'] # 意大利干酪 灰姑娘 沙门氏菌
  15. # 5
  16. things[1] = things[1].capitalize()
  17. print(things)
  18. # 6
  19. things[0] = things[0].upper()
  20. print(things)
  21. # 7
  22. things.remove('salmonella')
  23. print(things)
  24. # 8
  25. surprise = ['Groucho', 'Chico', 'Harpo']
  26. # 9
  27. surprise[-1] = surprise[-1].lower()[::-1].capitalize()
  28. print(surprise[-1])
  29. # 10
  30. e2f = {
  31. 'dog': 'chien',
  32. 'cat': 'chat',
  33. 'walrus': 'morse'
  34. }
  35. # 11
  36. for (key, value) in e2f.items():
  37. if key == 'walrus':
  38. print(value)
  39. # 12
  40. f2e = {}
  41. for (key, value) in e2f.items():
  42. f2e[value] = key
  43. print(f2e)
  44. # 13
  45. for (key, value) in f2e.items():
  46. if key == 'chien':
  47. print(value)
  48. # 14
  49. eng = [k for k in e2f.keys()]
  50. print(eng)
  51. # 15
  52. life = {
  53. 'animals': {
  54. 'cats': ['Henri', 'Grumpy', 'Lucy'],
  55. 'octopi': {},
  56. 'emus': {}
  57. },
  58. 'plants': {},
  59. 'others': {}
  60. }
  61. # 16
  62. print(life.keys())
  63. # 17
  64. print(life['animals'].keys())
  65. # 18
  66. print(life['animals']['cats'])

第四章

4.13 练习
(1) 将7 赋值给变量guess_me,然后写一段条件判断(if、else 和elif)的代码:如果
guess_me 小于7 输出'too low';大于7 则输出'too high';等于7 则输出'just right'。
(2) 将7 赋值给变量guess_me,再将1 赋值给变量start。写一段while 循环代码,比较start
和guess_me:如果start 小于guess_me,输出too low; 如果等于则输出'found it!' 并终
止循环;如果大于则输出'oops',然后终止循环。在每次循环结束时自增start。
(3) 使用for 循环输出列表[3, 2, 1, 0] 的值。
(4) 使用列表推导生成0~9(range(10))的偶数列表。
(5) 使用字典推导创建字典squares,把0~9(range(10))的整数作为键,每个键的平方作
为对应的值。
(6) 使用集合推导创建集合odd,包含0~9(range(10))的奇数。
(7) 使用生成器推导返回字符串'Got ' 和0~9 内的一个整数,使用for 循环进行迭代。
(8) 定义函数good:返回列表['Harry','Ron','Hermione']。
(9) 定义一个生成器函数get_odds:返回0~9 内的奇数。使用for 循环查找并输出返回的第
三个值。
(10) 定义一个装饰器test:当一个函数被调用时输出'start',当函数结束时输出'end'。
(11) 定义一个异常OopsException:编写代码捕捉该异常,并输出'Caught an oops'。
(12) 使用函数zip() 创建字典movies:匹配两个列表 titles = ['Creature of Habit',
'Crewel Fate'] 和plots = ['A nun turns into a monster', 'A haunted yarn shop']。

  1. """
  2. @author: jtahstu
  3. @contact: root@jtahstu.com
  4. @site: http://www.jtahstu.com
  5. @time: 2018/1/9 15:18
  6. """
  7. # 1
  8. guess_me = 7
  9. if guess_me < 7:
  10. print('too low')
  11. elif guess_me > 7:
  12. print('too high')
  13. else:
  14. print('just right')
  15. # 2
  16. start = 1
  17. while (True):
  18. if start < guess_me:
  19. print('too low')
  20. start += 1
  21. else:
  22. if start == guess_me:
  23. print('found it!')
  24. elif start > guess_me:
  25. print('oops')
  26. break
  27. # 3
  28. for i in [3, 2, 1, 0]:
  29. print(i)
  30. # 4
  31. odd = [i for i in range(10) if i % 2 == 0]
  32. print(odd)
  33. # 5
  34. squares = {x: x ** 2 for x in range(10)}
  35. print(squares)
  36. # 6
  37. odd = {j for j in range(10) if j % 2 == 1}
  38. print(odd)
  39. # 7
  40. def my_range():
  41. yield 'Got'
  42. for k in range(10):
  43. yield k
  44. myrange = my_range()
  45. for i in myrange:
  46. print(i, end=' ')
  47. print()
  48. # 8
  49. def good():
  50. return ['Harry', 'Ron', 'Hermione']
  51. # 9
  52. def get_odds():
  53. for l in range(10):
  54. if l & 1:
  55. yield l
  56. j = 0
  57. for i in get_odds():
  58. j += 1
  59. if j == 3:
  60. print(i)
  61. # 10
  62. def document_it(func):
  63. def new_func(*args, **kwargs):
  64. print('start')
  65. res = func(*args, **kwargs)
  66. print(res)
  67. print('end')
  68. return res
  69. return new_func
  70. new_good = document_it(good) # good 是第8步创建的函数
  71. new_good()
  72. # 11
  73. class OopsException(Exception):
  74. pass
  75. try:
  76. raise OopsException('Caught an oops')
  77. except OopsException as e:
  78. print(e)
  79. # 12
  80. titles = ['Creature of Habit', 'Crewel Fate']
  81. plots = ['A nun turns into a monster', 'A haunted yarn shop']
  82. for title, plot in zip(titles, plots):
  83. print(title, plot)

第五章

5.7 练习
(1) 创建文件zoo.py。在该文件中定义函数hours(),输出字符串'Open 9-5 daily'。然后
使用交互式解释器导入模块zoo 并调用函数hours()。
(2) 在交互式解释器中,把模块zoo 作为menagerie 导入,然后调用函数hours()。
(3) 依旧在解释器中,直接从模块zoo 导入函数hours() 并调用。
(4) 把函数hours() 作为info 导入,然后调用它。
(5) 创建字典plain,包含键值对'a':1、'b':2 和'c':3,然后输出它。
(6) 创建有序字典fancy:键值对和练习(5) 相同,然后输出它。输出顺序和plain 相
同吗?
(7) 创建默认字典dict_of_lists,传入参数list。给dict_of_lists['a'] 赋值'something
for a',输出dict_of_lists['a'] 的值。

  1. 2018_1 git:(master) python3
  2. Python 3.6.3 (v3.6.3:2c5fed86e0, Oct 3 2017, 00:32:08)
  3. [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
  4. Type "help", "copyright", "credits" or "license" for more information.
  5. # 1
  6. >>> import zoo
  7. >>> zoo.hours()
  8. Open 9-5 daily
  9. # 2
  10. >>> import zoo as menagerie
  11. >>> menagerie.hours()
  12. Open 9-5 daily
  13. # 3
  14. >>> from zoo import hours
  15. >>> hours()
  16. Open 9-5 daily
  17. # 4
  18. >>> from zoo import hours as info
  19. >>> info()
  20. Open 9-5 daily
  21. # 5
  22. plain = {
  23. 'a': 1,
  24. 'b': 2,
  25. 'c': 3
  26. }
  27. print(plain)
  28. # 6
  29. from collections import OrderedDict
  30. fancy = OrderedDict(plain) # 有序字典,按键排序
  31. print(fancy)
  32. # 7 如果本人没理解错的话,感觉这道题好智障
  33. dict_of_lists = plain
  34. dict_of_lists['a'] = 'something for a'
  35. print(dict_of_lists['a'])

第六章

6.15 练习
(1) 创建一个名为Thing 的空类并将它打印出来。接着,创建一个属于该类的对象example,
同样将它打印出来。看看这两次打印的结果是一样的还是不同的?
(2) 创建一个新的类Thing2,将'abc' 赋值给类特性letters,打印letters。
(3) 再创建一个新的类,叫作Thing3。这次将'xyz' 赋值给实例(对象)特性letters,并
试着打印letters。看看你是不是必须先创建一个对象才可以进行打印操作?
(4) 创建一个名为Element 的类,它包含实例特性name、symbol 和number。使用'Hydrogen'、
'H' 和1 实例化一个对象。
(5) 创建一个字典,包含这些键值对:'name': 'Hydrogen'、'symbol': 'H' 和'number': 1。
然后用这个字典实例化Element 类的对象hydrogen。
(6) 为Element 类定义一个dump() 方法,用于打印对象的特性(name、symbol 和number)。
使用这个新定义的类创建一个对象hydrogen 并用dump() 打印。
(7) 调用print(hydrogen),然后修改Element 的定义,将dump 方法的名字改为__str__。
再次创建一个hydrogen 对象并调用print(hydrogen),观察输出结果。
(8) 修改Element 使得name、symbol 和number 特性都变成私有的。为它们各定义一个getter
属性来返回各自的值。
(9) 定义三个类Bear、Rabbit 和Octothorpe。对每个类都只定义一个方法eats(),分别返
回'berries'(Bear)、'clover'(Rabbit)和'campers'(Octothorpe)。为每个类创建
一个对象并输出它们各自吃的食物(调用eats())。
(10) 定义三个类Laser、Claw 以及SmartPhone。每个类都仅有一个方法does(),分别返回
'disintegrate'(Laser)、'crush'(Claw) 以及'ring'(SmartPhone)。接着, 定义
Robot 类,包含上述三个类的实例(对象)各一个。给Robot 定义does() 方法用于输
出它各部分的功能。

  1. """
  2. @author: jtahstu
  3. @contact: root@jtahstu.com
  4. @site: http://www.jtahstu.com
  5. @time: 2018/1/9 17:11
  6. """
  7. # 1
  8. from pprint import pprint
  9. class Thing:
  10. pass
  11. print(Thing)
  12. example = Thing()
  13. print(example)
  14. # 2
  15. class Thing2:
  16. def __init__(self, letters):
  17. self.letters = letters
  18. l = Thing2('abc')
  19. print(l.letters)
  20. # 3 那肯定要先有个对象啊
  21. class Thing3:
  22. def __init__(self, letters):
  23. self.letters = letters
  24. ll = Thing3('xyz')
  25. print(ll.letters)
  26. # 4
  27. class Element:
  28. def __init__(self, name, symbol, number):
  29. self.name = name
  30. self.symbol = symbol
  31. self.number = number
  32. def dump(self):
  33. print('dump -> ', self.name, self.symbol, self.number)
  34. def __str__(self):
  35. print('__str__ -> ', self.name, self.symbol, self.number)
  36. return self.name
  37. obj = Element('Hydrogen', 'H', 1)
  38. # 5 用字典来构造一个命名元组
  39. dic = {
  40. 'name': 'Hydrogen',
  41. 'symbol': 'H',
  42. 'number': 1
  43. }
  44. hydrogen = Element(**dic)
  45. print(hydrogen.name, hydrogen.symbol, hydrogen.number)
  46. # 6 方法定义在问题4里
  47. hydrogen.dump()
  48. # 7 方法见问题4,这里打印的是 return 返回的东西
  49. print(hydrogen)
  50. # 8
  51. class Element2:
  52. def __init__(self, name, symbol, number):
  53. self.__name = name
  54. self.__symbol = symbol
  55. self.__number = number
  56. @property
  57. def name(self):
  58. return self.__name
  59. @property
  60. def symbol(self):
  61. return self.__symbol
  62. @property
  63. def number(self):
  64. return self.__number
  65. ele2 = Element2('jtahstu', 'J', 96)
  66. print('getter -> ', ele2.name, ele2.symbol, ele2.number)
  67. # 9
  68. class Bear:
  69. def eats(self):
  70. return 'berries'
  71. class Rabbit:
  72. def eats(self):
  73. return 'clover'
  74. class Octothorpe:
  75. def eats(self):
  76. return 'campers'
  77. a = Bear()
  78. b = Rabbit()
  79. c = Octothorpe()
  80. print(a.eats(), b.eats(), c.eats())
  81. # 10
  82. class Laser:
  83. def does(self):
  84. return 'disintegrate'
  85. class Claw:
  86. def does(self):
  87. return 'crush'
  88. class SmartPhone:
  89. def does(self):
  90. return 'ring'
  91. class Robot:
  92. def __init__(self, laser, claw, smartphonr):
  93. self.laser = laser
  94. self.claw = claw
  95. self.smartphonr = smartphonr
  96. def does(self):
  97. print('robot -> ', self.laser.does(), self.claw.does(), self.smartphonr.does())
  98. d = Laser()
  99. e = Claw()
  100. f = SmartPhone()
  101. robot = Robot(d, e, f)
  102. robot.does()

第七章

7.3 练习
(1) 创建一个Unicode 字符串mystery 并将它的值设为'\U0001f4a9'。打印mystery,并查
看mystery 的Unicode 名称。
(2) 使用UTF-8 对mystery 进行编码,存入字节型变量pop_bytes,并将它打印出来。
(3) 使用UTF-8 对pop_bytes 进行解码,存入字符串型变量pop_string,并将它打印出来,
看看它与mystery 是否一致?
(4) 使用旧式格式化方法生成下面的诗句,把'roast beef'、'ham'、'head' 和'clam' 依次
插入字符串:
My kitty cat likes %s,
My kitty cat likes %s,
My kitty cat fell on his %s
And now thinks he's a %s.
(5) 使用新式格式化方法生成下面的套用信函,将下面的字符串存储为letter(后面的练
习中会用到):
Dear {salutation} {name},
Thank you for your letter. We are sorry that our {product} {verbed} in your
{room}. Please note that it should never be used in a {room}, especially
near any {animals}.
Send us your receipt and {amount} for shipping and handling. We will send
you another {product} that, in our tests, is {percent}% less likely to
have {verbed}.
Thank you for your support.
Sincerely,
{spokesman}
{job_title}
(6) 创建一个字典response 包含以下键:'salutaion'、'name'、'product'、'verved'(动
词过去式)、'room'、'animals'、'amount'、'percent'、'spokesman' 以及'job_title'。
设定这些键对应的值,并打印由response 的值填充的letter。
(7) 正则表达式在处理文本上非常方便,在这个练习中我们会对示例文本尝试做各种
各样的操作。示例文本是一首诗,名为Ode on the Mammoth Cheese,作者是James
McIntyre,写于1866 年。出于对当时安大略湖手工制造的7000 磅的巨型奶酪的敬意,
它当时甚至在全球巡回展出。如果你不愿意自己一词一句敲出来,直接百度一下粘贴
到你的Python 代码里即可。你也可以从Project Gutenberg(http://www.gutenberg.org/
ebooks/36068?msg=welcome_stranger)找到。我们将这个字符串命名为mammoth。
We have seen thee, queen of cheese,
Lying quietly at your ease,
Gently fanned by evening breeze,
Thy fair form no flies dare seize.
All gaily dressed soon you'll go
To the great Provincial show,
To be admired by many a beau
In the city of Toronto.
Cows numerous as a swarm of bees,
Or as the leaves upon the trees,
It did require to make thee please,
And stand unrivalled, queen of cheese.
May you not receive a scar as
We have heard that Mr. Harris
Intends to send you off as far as
The great world's show at Paris.
Of the youth beware of these,
For some of them might rudely squeeze
And bite your cheek, then songs or glees
We could not sing, oh! queen of cheese.
We'rt thou suspended from balloon,
You'd cast a shade even at noon,
Folks would think it was the moon
About to fall and crush them soon.
(8) 引入re 模块以便使用正则表达式相关函数。使用re.findall() 打印出所有以c 开头的
单词。
(9) 找到所有以c 开头的4 个字母的单词。
(10) 找到所有以r 结尾的单词。
(11) 找到所有包含且仅包含3 个元音的单词。
(12) 使用unhexlify 将下面的十六进制串(出于排版原因将它们拆成两行字符串)转换为
bytes 型变量,命名为gif:
'47494638396101000100800000000000ffffff21f9' +
'0401000000002c000000000100010000020144003b'
(13) gif 定义了一个1 像素的透明GIF 文件(最常见的图片格式之一)。合法的GIF 文件开
头由GIF89a 组成,检测一下上面的gif 是否为合法的GIF 文件?
(14) GIF 文件的像素宽度是一个16 比特的以大端方案存储的整数,偏移量为6 字节,高度
数据的大小与之相同,偏移量为8。从gif 中抽取这些信息并打印出来,看看它们是
否与预期的一样都为1 ?

  1. """
  2. @author: jtahstu
  3. @contact: root@jtahstu.com
  4. @site: http://www.jtahstu.com
  5. @time: 2018/1/10 13:17
  6. """
  7. # 1
  8. mystery = '\U0001f4a9'
  9. print(mystery)
  10. import unicodedata
  11. print(unicodedata.name(mystery))
  12. # 2
  13. pop_bytes = mystery.encode('utf-8')
  14. print(pop_bytes)
  15. # 3
  16. pop_string = pop_bytes.decode('utf-8')
  17. print(pop_string)
  18. # 4
  19. print("My kitty cat likes %s,My kitty cat likes %s,My kitty cat fell on his %sAnd now thinks he's a %s." % (
  20. 'roast beef', 'ham', 'head', 'clam'))
  21. # 5 这里大括号要加 0[],不然格式化输出报错
  22. letter = """
  23. Dear {0[salutation]} {0[name]},
  24. Thank you for your letter. We are sorry that our {0[product]} {0[verbed]} in your
  25. {0[room]}. Please note that it should never be used in a {0[room]}, especially
  26. near any {0[animals]}.
  27. Send us your receipt and {0[amount]} for shipping and handling. We will send
  28. you another {0[product]} that, in our tests, is {0[percent]}% less likely to
  29. have {0[verbed]}.
  30. Thank you for your support.
  31. Sincerely,
  32. {0[spokesman]}
  33. {0[job_title]}
  34. """
  35. # 6
  36. response = {
  37. 'salutation': 'A',
  38. 'name': 'B',
  39. 'product': 'C',
  40. 'verbed': 'D',
  41. 'room': 'E',
  42. 'animals': 'F',
  43. 'amount': 'G',
  44. 'percent': 'H',
  45. 'spokesman': 'I',
  46. 'job_title': 'J'
  47. }
  48. print(letter.format(response))
  49. # 7
  50. mammoth = """
  51. We have seen thee, queen of cheese,
  52. Lying quietly at your ease,
  53. Gently fanned by evening breeze,
  54. Thy fair form no flies dare seize.
  55. All gaily dressed soon you'll go
  56. To the great Provincial show,
  57. To be admired by many a beau
  58. In the city of Toronto.
  59. Cows numerous as a swarm of bees,
  60. Or as the leaves upon the trees,
  61. It did require to make thee please,
  62. And stand unrivalled, queen of cheese.
  63. May you not receive a scar as
  64. We have heard that Mr. Harris
  65. Intends to send you off as far as
  66. The great world's show at Paris.
  67. Of the youth beware of these,
  68. For some of them might rudely squeeze
  69. And bite your cheek, then songs or glees
  70. We could not sing, oh! queen of cheese.
  71. We'rt thou suspended from balloon,
  72. You'd cast a shade even at noon,
  73. Folks would think it was the moon
  74. About to fall and crush them soon. cwr3 aiu 3xxr
  75. """
  76. # 8 以 c 开头的单词
  77. import re
  78. cs = re.findall(r'\bc.*?\b', mammoth)
  79. print(cs)
  80. # 9 找到所有以 c 开头的4个字母的单词
  81. cw = re.findall(r'\bc[a-zA-Z]{3}\b', mammoth)
  82. print(cw)
  83. # 10 找到所有以 r 结尾的单词
  84. r = re.findall(r'\b[a-zA-Z]*?r\b', mammoth)
  85. print(r)
  86. # 11 找到所有包含且仅包含 3 个元音的单词
  87. y = re.findall(r'\b[aoeiu]{3}\b', mammoth)
  88. print(y)
  89. # 12
  90. import binascii
  91. gif = binascii.unhexlify(b'47494638396101000100800000000000ffffff21f90401000000002c000000000100010000020144003b')
  92. gif = bytes(gif) # b'GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x01D\x00;'
  93. # 13
  94. print(gif[0:6] == b'GIF89a') # True
  95. # 14 这里应该表示6 7和8 9,都为\x01\x00,因为是大端方案存储
  96. print(gif[6:10]) # b'\x01\x00\x01\x00'

第八章

8.7 练习
(1) 将字符串'This is a test of the emergency text system' 赋给变量test1,然后把它写到文件test.txt。
(2) 打开文件test.txt,读文件内容到字符串test2。test1 和test2 是一样的吗?
(3) 保存这些文本到books.csv文件。注意,字段间是通过逗号隔开的,如果字段中含有逗号需要在整个字段加引号。
author,book
J R R Tolkien,The Hobbit
Lynne Truss,"Eats, Shoots & Leaves"
(4) 使用csv 模块和它的DictReader方法读取文件books.csv到变量books。输出变量books的值。DictReader 可以处理第二本书题目中的引号和逗号吗?
(5) 创建包含下面这些行的CSV 文件books.csv:
title,author,year
The Weirdstone of Brisingamen,Alan Garner,1960
Perdido Street Station,China Miéville,2000
Thud!,Terry Pratchett,2005
The Spellman Files,Lisa Lutz,2007
Small Gods,Terry Pratchett,1992
(6) 使用sqlite3 模块创建一个SQLite 数据库books.db 以及包含字段title(text)、author
(text)以及year(integer)的表单books。
(7) 读取文件books.csv,把数据插入到表单book。
(8) 选择表单book 中的title 列,并按照字母表顺序输出。
(9) 选择表单book 中所有的列,并按照出版顺序输出。
(10) 使用sqlalchemy 模块连接到sqlite3 数据库books.db,按照(8) 一样,选择表单book 中
的title 列,并按照字母表顺序输出。
(11) 在你的计算机安装Redis 服务器和Python 的redis 库(pip install redis)。创建一
个Redis 的哈希表test,包含字段count(1) 和name('Fester Bestertester'),输出
test 的所有字段。
(12) 自增test 的count 字段并输出它。

  1. """
  2. @author: jtahstu
  3. @contact: root@jtahstu.com
  4. @site: http://www.jtahstu.com
  5. @time: 2018/1/10 15:09
  6. """
  7. # 1
  8. from pprint import pprint
  9. test1 = 'This is a test of the emergency text system'
  10. testw = open('test.txt', 'wt')
  11. testw.write(test1)
  12. testw.close()
  13. # 2
  14. with open('test.txt', 'rt') as testr:
  15. test2 = testr.read()
  16. print(test2 == test1) # True
  17. # 3
  18. bookstr = """author,book
  19. J R R Tolkien,The Hobbit
  20. Lynne Truss,"Eats, Shoots & Leaves"
  21. """
  22. with open('books.csv', 'wt') as testc:
  23. testc.write(bookstr)
  24. # 4 第二本书引号没了,但是逗号没有被分割
  25. import csv
  26. with open('books.csv', 'rt') as fin:
  27. cin = csv.DictReader(fin)
  28. books = [row for row in cin]
  29. print(books)
  30. # 5 名字为 book2.csv
  31. # 6
  32. import sqlite3
  33. conn = sqlite3.connect('books.db')
  34. curs = conn.cursor()
  35. # curs.execute('''CREATE TABLE books
  36. # (title TEXT,
  37. # author TEXT,
  38. # year INT)''')
  39. # 7 原字符串中含有é,导致读出的时候显示编码错误,就替换掉了
  40. bookstr2 = """title,author,year
  41. The Weirdstone of Brisingamen,Alan Garner,1960
  42. Perdido Street Station,China Mieville,2000
  43. Thud!,Terry Pratchett,2005
  44. The Spellman Files,Lisa Lutz,2007
  45. Small Gods,Terry Pratchett,1992
  46. """
  47. with open('books2.csv', 'wt') as testc2:
  48. testc2.write(bookstr2)
  49. sql = "insert into books(title,author,year) values (?,?,?)"
  50. with open('books2.csv', 'rt') as cb:
  51. dicts = csv.reader(cb)
  52. books2 = [row for row in dicts]
  53. print(books2[1:])
  54. for d in books2[1:]:
  55. res = curs.execute(sql, (d[0], d[1], int(d[2])))
  56. print(res)
  57. conn.commit() # 这里 commit一下可以把数据写入到文件,不然数据就只存在与内存中
  58. # 8
  59. curs.execute('SELECT title FROM books ORDER BY title')
  60. rows = curs.fetchall()
  61. pprint(rows) # 为什么这里输出多了个逗号,不太清楚
  62. # 9
  63. curs.execute('SELECT * FROM books ORDER BY year')
  64. rows2 = curs.fetchall()
  65. pprint(rows2)
  66. curs.close()
  67. conn.close()
  68. # 以下三个问题都没测试,因为模块没装,但感觉问题不大
  69. # 10
  70. import sqlalchemy as sa
  71. conn2 = sa.create_engine('sqlite://')
  72. rows3 = conn.execute('SELECT title FROM books ORDER BY title')
  73. for row in rows3:
  74. print(row)
  75. # 11
  76. import redis
  77. conn3 = redis.Redis()
  78. conn3.hset('test', {'count': 1, 'name': 'Fester Bestertester'})
  79. print(conn.hget('test'))
  80. # 12
  81. conn3.hincr('test', 'count')

第九章

9.4 练习
(1) 如果你还没有安装flask,现在安装它。这样会自动安装werkzeug、jinja2 和其他包。
(2) 搭建一个网站框架,使用Flask 的调试/ 代码重载来开发Web 服务器。使用主机名
localhost 和默认端口5000 来启动服务器。如果你电脑的5000 端口已经被占用,使用
其他端口。
(3) 添加一个home() 函数来处理对于主页的请求,让它返回字符串It's alive!。
(4) 创建一个名为home.html 的Jinja2 模板文件,内容如下所示:

  1. <html>
  2. <head>
  3. <title>It's alive!</title>
  4. <body>
  5. I'm of course referring to {{thing}}, which is {{height}} feet tall and {{color}}.
  6. </body>
  7. </html>

(5) 修改home() 函数,让它使用home.html 模板。给模板传入三个GET 参数:thing、height
和color。

  1. """
  2. @author: jtahstu
  3. @contact: root@jtahstu.com
  4. @site: http://www.jtahstu.com
  5. @time: 2018/1/11 11:33
  6. """
  7. from flask import Flask, render_template, request
  8. app = Flask(__name__)
  9. @app.route('/')
  10. def home():
  11. # 3
  12. # return "It's alive!"
  13. # 4
  14. k = {}
  15. k['thing'] = request.args.get('thing')
  16. k['height'] = request.args.get('height')
  17. k['color'] = request.args.get('color')
  18. return render_template('home.html', **k) # 创建templates/home.html文件
  19. app.run(port=5000, debug=True)

第十章

10.5 练习
(1) 把当前日期以字符串形式写入文本文件today.txt。
(2) 从today.txt 中读取字符串到today_string 中。
(3) 从today_string 中解析日期。
(4) 列出当前目录下的文件。
(5) 列出父目录下的文件。
(6) 使用multiprocessing 创建三个进程,让它们等待随机的秒数(范围1~5),打印出当前
时间并退出。
(7) 用你的生日创建一个date 对象。
(8) 你的生日是星期几?
(9) 你出生10 000 天的日期是什么?

  1. """
  2. @author: jtahstu
  3. @contact: root@jtahstu.com
  4. @site: http://www.jtahstu.com
  5. @time: 2018/1/11 13:48
  6. """
  7. from datetime import datetime, date
  8. # 1 把当前日期以字符串形式写入文本文件today.txt
  9. now = datetime.today()
  10. with open('today.txt', 'wt') as w:
  11. res = w.write(str(now))
  12. print(res)
  13. # 2 从today.txt 中读取字符串到today_string 中
  14. with open('today.txt', 'rb') as r:
  15. today_string = r.readline().decode('utf-8')
  16. print(today_string)
  17. # 3 从today_string 中解析日期
  18. dateNow = datetime.strptime(today_string, "%Y-%m-%d %H:%M:%S.%f").date()
  19. print(dateNow)
  20. # 4 列出当前目录下的文件
  21. import os
  22. files = [file for file in os.listdir('.') if os.path.isfile(file)]
  23. print(files)
  24. # 5 列出父目录下的文件
  25. filesP = [file for file in os.listdir('../') if os.path.isfile(file)]
  26. print(filesP)
  27. # 6 使用multiprocessing 创建三个进程,让它们等待随机的秒数(范围1~5),打印出当前时间并退出
  28. import multiprocessing
  29. from time import sleep
  30. import random
  31. def p(i):
  32. sleep(random.randrange(1, 5))
  33. print('process %d , now is %s' % (i, str(datetime.today())))
  34. quit(0)
  35. for i in range(3):
  36. pc = multiprocessing.Process(target=p, args=(i,))
  37. pc.start()
  38. # 7 用你的生日创建一个date 对象
  39. birthday = date(1995, 10, 29)
  40. # 8 你的生日是星期几?
  41. dayOfWeek = birthday.weekday()
  42. print(dayOfWeek)
  43. # 9 你出生10 000 天的日期是什么?
  44. from datetime import timedelta
  45. birthday1000 = birthday + timedelta(days=1000)
  46. print(birthday1000)

第十一章

pass,粗略看了一下,不想写

第十二章

没有了,大吉大利,今晚吃鸡!

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注