【Python爬虫】-笨办法学 Python 习题39-41

一、作业内容

笨办法学 Python 习题39-41以及加分题。

二、作业代码:

# 习题 39: 列表的操作
ten_things = "Apples Oranges Crows Telephone Light sugar"

print("Wait there's not 10 things in that list, let's fix that.")
# ten_things.split(' ')其实是.split(ten_things, ' ')
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]

while len(stuff) != 10:
    next_one = more_stuff.pop()
    print("Adding: ", next_one)
    stuff.append(next_one)
    print("There's %d items now." % len(stuff))

print("There we go: ", stuff)

print("Let's do some things with stuff.")

print(stuff[1])
print(stuff[-1])
print(stuff.pop())
print(' '.join(stuff))
print('#'.join(stuff[3:5]))
加分习题
1.将每一个被调用的函数以上述的方式翻译成 Python 实际执行的动作。例如: ' '.join(things) 其实是 join(' ', things) 。
2.将这两种方式翻译为自然语言。例如, ' '.join(things) 可以翻译成“用 ‘ ‘ 连接(join) things”,而 join(' ', things) 的意思是“为 ‘ ‘ 和 things 调用 join 函数”。这其实是同一件事情。
3.上网阅读一些关于“面向对象编程(Object Oriented Programming)”的资料。晕了吧?嗯,我以前也是。别担心。你将从这本书学到足够用的关于面向对象编程的基础知识,而以后你还可以慢慢学到更多。
4.查一下 Python中的 “class” 是什么东西。不要阅读关于其他语言的 “class” 的用法,这会让你更糊涂。
5.dir(something) 和 something 的 class 有什么关系?
6.如果你不知道我讲的是些什么东西,别担心。程序员为了显得自己聪明,于是就发明了 Opject Oriented Programming,简称为 OOP,然后他们就开始滥用这个东西了。如果你觉得这东西太难,你可以开始学一下 “函数编程(functional programming)”。
# 加分习题1.2.
ten_things = "Apples Oranges Crows Telephone Light sugar"

print("Wait there's not 10 things in that list, let's fix that.")

# ten_things.split(' ') 其实是split(ten_things, ' ')
# ten_things.split(' ') 翻译为:用ten_things split(分割) ' '
# split(ten_things, ' ') 翻译为:为ten_things和' '调用split(分割)函数
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]

while len(stuff) != 10:
    next_one = more_stuff.pop()
    print("Adding: ", next_one)

    # stuff.append(next_one)其实是append(stuff, next_one)
    # stuff.append(next_one) 翻译为:用stuff append(增加)next_one
    # append(stuff, next_one) 翻译为:为stuff和next_one调用append函数
    stuff.append(next_one)
    print("There's %d items now." % len(stuff))

print("There we go: ", stuff)

print("Let's do some things with stuff.")

print(stuff[1])
print(stuff[-1])

# stuff.pop()其实是pop(stuff)
# stuff.pop()翻译为:用stuff pop(删除)
# pop(stuff)翻译为:为stuff调用pop函数

print(stuff.pop())
# ' '.join(stuff)其实是join(' ', stuff)
# ' '.join(stuff)翻译为:用' 'join(连接)stuff
# join(' ', stuff)翻译为:为' '和stuff调用join函数
print(' '.join(stuff))
# '#'.join(stuff[3:5])其实是join('#', stuff[3:5])
# '#'.join(stuff[3:5])翻译为:用'#'join(连接)stuff[3:5]
# join('#', stuff[3:5])翻译为:为'#'和stuff[3:5]调用join函数
print('#'.join(stuff[3:5]))

# 加分习题4.
# class(类)
class Student(object):
    # 1.__init__方法的第一个参数永远是self,表示创建的实例本身
    # 2.在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身
    def __init__(self, name, score):
        self.name = name
        self.score = score

# 有了__init__方法,在创建实例的时候不能传入空的参数
# 必须传入与__init__方法匹配的参数,但self不需要传,Python解释器自己会把实例变量传进去
bart = Student('Bart Simpson', 59)

print(bart.name)
print(bart.score)
# 习题 40: 字典, 可爱的字典
# dict
cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'}

cities['NY'] = 'New York'
cities['OR'] = 'Portland'

def find_city(themap, state):
    # 条件判断
    if state in themap:
        return themap[state]
    else:
        return "Not found."

cities['_find'] = find_city

while True:
    print("State? (ENTER to quit)")
    state = input("> ")

    if not state: break

    city_found = cities['_find'](cities, state)
    print(city_found)

运行结果如下:

"C:\Program Files\Python36\python.exe" E:/python3_project/ex40.py
State? (ENTER to quit)
> CA
San Francisco
State? (ENTER to quit)
> FL
Jacksonville
State? (ENTER to quit)
> 0
Not found.
State? (ENTER to quit)
> OR
Portland
State? (ENTER to quit)
> VT
Not found.
State? (ENTER to quit)
> 
加分习题
1.在 Python 文档中找到 dictionary (又被称作 dicts, dict)的相关的内容,学着对 dict 做更多的操作。
2.找出一些 dict 无法做到的事情。例如比较重要的一个就是 dict 的内容是无序的,你可以检查一下看看是否真是这样。
3.试着把 for-loop 执行到 dict 上面,然后试着在 for-loop 中使用 dict 的 items() 函数,看看会有什么样的结果。
# 加分题1
Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
# 1.把数据放入dict的方法,除了初始化时指定外,还可以通过key放入
# 2.但要保证变量d已被字典所赋值的前提才不会报错。
>>> d['Adam'] = 67
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'd' is not defined

>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
通过 字典[key] 可得到value的值
>>> d['Michael']
95
>>> d['Adam'] = 67
>>> d['Adam']
67
>>> d['Jack'] = 90
>>> d['Jack']
90
由于一个key只能对应一个value,所以多次对一个key放入value,后面的值会把前面的值冲掉:
>>> d['Jack'] = 88
>>> d['Jack']
88
如果key不存在,dict就会报错
>>> d['Ubuay']
Traceback (most recent call last):
  File "", line 1, in 
KeyError: 'Ubuay'

要避免key不存在的错误,有两种方法,一时通过'in'判断key是否存在:
>>> 'Ubuay' in d
False
1.二是通过dict提供的get方法,如果key不存在,可以返回None
2.返回'None'的时候Python的交互式命令行不显示结果
>>> d.get('Ubuay')
>>>
你也可以自己指定的value:意思是当如果key不存在,可以返回你指定的value
>>> d.get('Ubuay', -1)
-1

要删除一个key,用pop(key)方法,对应的value也会从dict中删除:
>>> d.pop('Bob')
75
>>> d
{'Michael': 95, 'Tracy': 85, 'Adam': 67, 'Jack': 88}

>>> d.get('Ubuay')
>>> d.get('Ubuay', -1)
-1

1.第一行设定了key
2.第二行改变key,发现不可改变
>>> key = [1, 2, 3]
>>> d[key] = 'a list'
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unhashable type: 'list'
>>>
# 习题 41: 来自 Percal 25 号行星的哥顿人
# 习题 41: 来自 Percal 25 号行星的哥顿人(Gothons)
# 通过from...import...导入sys模块,将exit直接导入程序
# 通过from...random...导入random模块,将randint直接导入程序
from sys import exit
from random import randint
# 定义death函数
def death():
    # 将列表赋值给变量quips
    quips = ["You died. You kinda suck at this.",
             "Nice job, you died ...jackass.",
             "Such a luser.",
             "I have a small puppy that's better at this."]
    # len() 方法返回quips列表项目个数(4)。并减1
    # random.randint(a, b),用于生成一个指定范围内的整数,
    # 其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b
    # 参数为(0, 3),生成的随机数n:0 <= n <= 3
    # quips[n]用索引来访问list中的一个元素,并打印出来
    print(quips[randint(0, len(quips)-1)])
    # exit(1):有错误退出
    exit(1)


# 定义central_corridor()函数
def central_corridor():
    # 打印字符串
    print("The Gothons of Planet Percal #25 have invaded your ship and destroy")
    print("you entire crew.  You are the last surviving member and your last")
    print("mission is to get the neutron destruct bomb from the Weapons Armory,")
    print("put it in the bridge, and blow the ship up after getting into an ")
    print("escape pod.")
    print("\n")
    print("You're running down the central corridor to the Weapons Armory when")
    print("a Gothon jumps put, red scaly skin, dark grimy teeth, and evil clown costume")
    print("flowing around his hate filled body. He's blocking the door to the")
    print("Armory and about to pull a weapon to blast you.")

    # 通过input("> ")命令输入值,并将值赋予action变量
    action = input("> ")

    # 通过if语句判断action变量的值是否等于shoot!字符串
    # 如果if语句判断为True,就把缩进print语句执行,并返回death字符串(忽略剩下的elif和else)
    # 如果if语句判断为False,执行elif(或else)语句
    if action == "shoot!":
        print("Quick on the draw you yank out your blaster and fire it at the Gothon.")
        print("His clown costume is flowing and moving around his body, which throws")
        print("off your aim.  Your laser hits his costume but misses him entirely.  This")
        print("completely ruins his brand new costume his mother bought him, which")
        print("makes him fly into an insane rage and blast you repeatedly in the face until")
        print("you are dead.  Then he eats you.")
        return 'death'

    # elif语句判断action变量的值是否等于dodge!字符串
    # 如果elif语句判断为True,就把缩进print语句执行,并返回death字符串(忽略剩下的elif和else)
    # 如果elif语句判断为False,执行下一个elif(或else)语句
    elif action == "dodge!":
        print("Like a world class boxer you dodge, weave, slip and slide right")
        print("as the Gothon's blaster cranks a laser past your head.")
        print("In the middle of your artful dodge your foot slips and you")
        print("bang your head on the metal wall and pass out.")
        print("You wake up shortly after only to die as the Gothon stomps on")
        print("your head and eats you.")
        return 'death'

    # elif语句判断action变量的值是否等于tell a joke字符串
    # 如果elif语句判断为True,就把缩进print语句执行,并返回laser_weapon_armory字符串(忽略剩下的elif和else)
    # 如果elif语句判断为False,执行剩下的else语句
    elif action == "tell a joke":
        print("Lucky for you they made you learn Gothon insults in the academy.")
        print("You tell the one Gothon joke you know:")
        print("Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr.")
        print("The Gothon stops, tries not to laugh, then busts out laughing and can't move.")
        print("While he's laughing you run up and shoot him square in the head")
        print("putting him down, then jump through the Weapon Armory door.")
        return 'laser_weapon_armory'
    # 打印DOES NOT COMPUTE!字符串
    # 返回central_corridor字符串
    else:
        print("DOES NOT COMPUTE!")
        return 'central_corridor'

# 定义laser_weapon_armory()函数
def laser_weapon_armory():
    # 打印字符串

    # random.randint(a, b),用于生成一个指定范围内的整数,
    # 其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b
    # 字符串包含 %d 格式化变量,变量名n均为:
    # 参数为(1, 9),生成的随机数:1 <= n <= 9
    # 将'%d%d%d'字符串赋值给code变量
    # 通过input("[keypad]> ")命令输入值,并将值赋予guess变量
    # 将0整数赋值给guesses变量
    print("You do a dive roll into the Weapon Armory, crouch and scan the room")
    print("for more Gothons that might be hiding.  It's dead quiet, too quiet.")
    print("You stand up and run to the far side of the room and find the")
    print("neutron bomb in its container.  There's a keypad lock on the box")
    print("and you need the code to get the bomb out.  If you get the code")
    print("wrong 10 times then the lock closes forever and you can't")
    print("get the bomb.  The code is 3 digits.")
    code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
    guess = input("[keypad]> ")
    guesses = 0

    # guess变量的值不等于code变量的值
    # and运算是与运算,所有都为True,and运算结果才是True
    # while语句,只要条件满足就不断循环缩进语句,条件不满足时退出循环
    # 即:guess变量的值不等于code变量的布尔值为True,guesses变量的值小于10的布尔值为True时,不断循环
    # 它们的and运算结果(其中一个条件布尔值)为False时退出循环
    while guess != code and guesses < 10:
        # 缩进语句:
        # 打印"BZZZZEDDD!"字符串
        # +=是加法赋值运算符,比如c += a 等效于 c = c + a
        # guesses += 1 等效于 guesses = guesses + 1,
        # 即:将guesses变量的值与1整数的值相加的结果存放到guesses变量
        # 通过input("[keypad]> ")命令输入值,并将值赋予guess变量
        print("BZZZZEDDD!")
        guesses += 1
        guess = input("[keypad]> ")

    # 通过if语句判断guess变量的值是否等于code变量的值:
    # 如果if语句判断为True,就把缩进print语句执行,并返回'the_bridge'字符串(忽略剩下的elif和else)
    # 如果if语句判断为False,执行elif或else语句
    if guess == code:
        print("The container clicks open and the seal breaks, letting gas out.")
        print("You grab the neutron bomb and run as fast you can to the")
        print("bridge_where you must place it in the right spot.")
        return 'the_bridge'

    # 打印字符串
    # 返回 'death'字符串
    else:
        print("The lock buzzes one last time and then you hear sickening")
        print("melting sound as the mechanism is fused together.")
        print("You decide to sit there, and finally the Gothons blow up the")
        print("ship from their ship and you die.")
        return 'death'

# 定义the_bridge()函数
def the_bridge():
    # 打印字符串
    print("You burst onto the Bridge with the neutron destruct bomb")
    print("under your arm and surprise 5 Gothons who are trying to")
    print("take control of the ship.  Each of them has an even uglier")
    print("clown costume than the last.  They haven't pulled their")
    print("weapons out yet, as they see the active bomb under your")
    print("arm and don't want to set it off.")

    # 通过input("> ")命令输入值,并将值赋予 action 变量
    action = input("> ")

    # 通过if语句判断 action 变量的值是否等于"throw the bomb"字符串的值:
    # 如果if语句判断为True,就把缩进print语句执行,并返回'death'字符串(忽略剩下的elif和else)
    # 如果if语句判断为False,执行elif或else语句
    if action == "throw the bomb":
        print("In a panic you throw the bomb at the group of Gothons")
        print("and make a leap for the door.  Right as you drop it a")
        print("Gothon shoots you right in the back killing you.")
        print("As you die you see another Gothon frantically try to disarm")
        print("the bomb. You die knowing they will probably blow up when")
        print("it goes off.")
        return 'death'

    # elif语句判断 action 变量的值是否等于"slowly place the bomb"字符串
    # 如果elif语句判断为True,就把缩进print语句执行,并返回'escape_pod'字符串(忽略剩下的elif和else)
    # 如果elif语句判断为False,执行下一个elif(或else)语句
    elif action == "slowly place the bomb":
        print("You point your blaster at the bomb under you arm")
        print("and the Gothons put their hands up and start to sweat.")
        print("You inch backward to the door, open it, and then carefully")
        print("place the bomb on the floor, pointing your blaster at it.")
        print("You then jump back through the door, punch the close button")
        print("and blast the lock so the Gothons can't get out.")
        print("Now that the bomb is placed you run to the escape pod to")
        print("get off this tin can.")
        return 'escape_pod'
    # 打印字符串
    # 返回"the_bright"字符串
    else:
        print("DOES NOT COMPUTE!")
        return "the_bright"

# 定义 escape_pod()函数
def escape_pod():
    # 打印字符串
    # 将randint(1,5)随机数赋值给good_pod变量
    # 通过input("[pod #]> ")命令输入值,并将值赋予 guess 变量
    print("You rush through the ship desperately trying to make it to")
    print("the escape pod before the whole ship explodes.  It seems like")
    print("hardly any Gothons are on the ship, so your run is clear of")
    print("interference.  You get to the chamber with the escape pods, and")
    print("now need to pick one to take.  Some of them could be damaged")
    print("but you don't have time to look.  There's 5 pods, which one")
    print("do you take?")

    good_pod = randint(1,5)
    guess = input("[pod #]> ")

    # 在上一段代码中input()返回的数据类型是str,str不能直接与整数比较,
    # 必须先把str转换成整数(注:int无法转换「不是合法数字」的字符串):
    # 通过if语句判断 int(guess) 变量的值是否不等于 good_pod 变量的值:
    # 如果if语句判断为True,就把缩进print语句执行,并返回'death'字符串(忽略剩下的elif和else)
    # 如果if语句判断为False,执行elif或else语句
    if int(guess) != good_pod:
        print("You jump into pod %s and hit the eject button." % guess)
        print("The pod escapes out into the world of space, then")
        print("implodes as the hull ruptures, crushing your body")
        print("into jam jelly.")
        return 'death'
    # 打印字符串
    # exit(0):无错误退出
    else:
        print("You jump into pod %s and hit the eject button." % guess)
        print("The pod easily slides out into space heading to")
        print("the planet below. Asit flies to the planet, you look")
        print("back and see you ship implode then explode like a")
        print("bright star, taking out the Gothon ship at the same")
        print("time. You won!")
        exit(0)

# 使用dict创建ROOMS字典,使用键-值(key-value)存储
ROOMS = {
    'death': death,
    'central_corridor': central_corridor,
    'laser_weapon_armory': laser_weapon_armory,
    'the_bridge': the_bridge,
    'escape_pod': escape_pod
}

# 定义函数runner()参数分别为map,start
def runner(map, start):
    # 将start变量赋值给next变量
    next = start

    # while语句,只要条件满足就不断循环缩进语句,条件不满足时退出循环
    while True:

        room = map[next]
        print("\n--------")
        next = room()

runner(ROOMS, 'central_corridor')
 

你可能感兴趣的:(【Python爬虫】-笨办法学 Python 习题39-41)