美文网首页Python三期爬虫作业
【Python爬虫】-第二周 习题 18-26

【Python爬虫】-第二周 习题 18-26

作者: 五虎谷的阿格2 | 来源:发表于2017-07-23 14:06 被阅读86次

    ex18

    代码

    #ex18命名、变量、代码、函数的练习
    
    # this one is like your script with argv
    def print_two(*args):
        arg1, arg2 = args
        print ("arg1: %r, arg2: %r" % (arg1, arg2))
    
    # ok,that *args is actually pointless, we can just do this  好吧,那一个实际上是毫无意义的,我们可以这样做
    def print_two_again(arg1, arg2):
        print("arg1: %r, arg2: %r" % (arg1, arg2))
    
    #this just takes one argument 这只需要一个参数
    def print_one(arg1):
        print("arg1: %r" % arg1)
    
    #this one takes no arguments 这个不需要参数
    def print_none():
        print("I got nothin'.")
    
    print_two("Zed", "Shaw")
    print_two_again("Zed", "Shaw")
    print_one("First")
    print_none()
    

    运行结果

    "C:\Program Files\Python36\python.exe" "D:/小克学习/python/项目/week two/ex18.py"
    arg1: 'Zed', arg2: 'Shaw'
    arg1: 'Zed', arg2: 'Shaw'
    arg1: 'First'
    I got nothin'.
    
    Process finished with exit code 0
    

    加分习题
    为自己写一个函数注意事项以供后续参考。你可以写在一个索引卡片上随时阅读,直到你记住所有的要
    点为止。注意事项如下:

    1. 函数定义是以 def 开始的吗?\是的,创建函数
    2. 函数名称是以字符和下划线 _ 组成的吗?\是的
    3. 函数名称是不是紧跟着括号 ( ? \是的
    4. 括号里是否包含参数?多个参数是否以逗号隔开?\可以
    5. 参数名称是否有重复?(不能使用重复的参数名)\不可以
    6. 紧跟着参数的是不是括号和冒号 ): ? \是的
    7. 紧跟着函数定义的代码是否使用了 4 个空格的缩进 (indent) ? \使用了
    8. 函数结束的位置是否取消了缩进 (“dedent”) ? \取消了
    当你运行(或者说“使用 use” 或者“调用 call” )一个函数时,记得检查下面的要点:
    1. 调运函数时是否使用了函数的名称? \没有
    2. 函数名称是否紧跟着 ( ? \没有
    3. 括号后有无参数?多个参数是否以逗号隔开?\可以
    4. 函数是否以 ) 结尾?\是的

    按照这两份检查表里的内容检查你的练习,直到你不需要检查表为止。
    最后,将下面这句话阅读几遍:
    “‘运行函数 (run)’ 、‘调用函数 (call)’ 、和 ‘使用函数 (use)’ 是同一个意思”

    ex19

    代码

    def cheese_and_crackers(cheese_count, boxes_of_crackers):
        print("You have %d cheesee!" % cheese_count)
        print("You have %d boxes of crackers!" % boxes_of_crackers)
        print("Man that's enough for a party!")#男人足够参加聚会了!
        print("Get a blanket.\n")#拿条毯子
    
    print("We can just give the funcation numbers directly:")#我们可以直接使用这些功能
    cheese_and_crackers(20, 30)
    
    print("Or, we can use variables from our script:")
    amount_of_cheese = 10
    amount_of_crackers = 50
    
    cheese_and_crackers(amount_of_cheese, amount_of_crackers)
    
    print("We can even do math inside too:")
    cheese_and_crackers(10 + 20, 5 + 6)
    
    print("And we can combine the two, variables and math:")#我们可以把这两个变量和数学结合起来
    cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
    

    运行结果

    "C:\Program Files\Python36\python.exe" "D:/小克学习/python/项目/week two/ex19.py"
    We can just give the funcation numbers directly:
    You have 20 cheesee!
    You have 30 boxes of crackers!
    Man that's enough for a party!
    Get a blanket.
    
    Or, we can use variables from our script:
    You have 10 cheesee!
    You have 50 boxes of crackers!
    Man that's enough for a party!
    Get a blanket.
    
    We can even do math inside too:
    You have 30 cheesee!
    You have 11 boxes of crackers!
    Man that's enough for a party!
    Get a blanket.
    
    And we can combine the two, variables and math:
    You have 110 cheesee!
    You have 1050 boxes of crackers!
    Man that's enough for a party!
    Get a blanket.
    
    
    Process finished with exit code 0
    
    

    加分习题

    1. 倒着将脚本读完,在每一行上面添加一行注解,说明这行的作用。
    2. 从最后一行开始,倒着阅读每一行,读出所有的重要字符来。

    ex20

    #ex20 函数和文件
    
    from sys import argv
    
    script, input_file = argv
    
    def print_all(f):
        print(f.read())
    
    def rewind(f):
        f.seek(0)
    
    def print_a_line(line_count, f):
        print(line_count, f.readline())
    
    current_file = open(input_file)
    
    print("First let's print the whole file:\n")#首先让我们打印整个文件
    
    print_all(current_file)
    
    print("Now let't rewind, kind of like a tape.")#现在让我们倒带,像磁带
    
    rewind(current_file)
    
    print("Let's print three lines:")#让我们打印3行
    
    current_line = 1
    print_a_line(current_line, current_file)
    
    current_line = current_line + 1
    print_a_line(current_line, current_file)
    
    current_line = current_line + 1
    print_a_line(current_line, current_file)
    

    代码运行

    "C:\Program Files\Python36\python.exe" "D:/小克学习/python/项目/week two/ex20.py" test.txt
    First let's print the whole file:
    
    随便填写点东西测试下,
    
    人生如雪,我学python!
    Now let't rewind, kind of like a tape.
    Let's print three lines:
    1 随便填写点东西测试下,
    
    2 
    
    3 人生如雪,我学python!
    
    Process finished with exit code 0
    
    

    因为我的test的文件和练习中的不同,所以代码运行的结果也不一样。

    ex21

    代码

    #ex21 函数可以返回东西
    
    def add(a, b):#加
        print("ADDING %d + %d" % (a, b))
        return a + b
    
    def subtract(a, b):#减去
        print("SUBTRACT %d - %d" % (a, b))
        return a - b
    
    def multiply(a, b):
        print("MULTIPLY %d * %d" % (a, b))
        return a * b
    
    def divide(a,b):
        print("DIVID %d / %d" % (a,b))
        return a / b
    
    print("Let's do some math with just functions!")
    
    age = add(30, 5)
    height = subtract(78, 4)
    weight = multiply(90, 2)
    iq = divide(100, 2)
    
    print("Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq))
    
    # A puzzle for the extra credit, type it in anyway #额外学分的一个难题,无论如何要输入它
    print("Here is a puzzle.")
    
    what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
    
    print("That becomes:", what, "Can you do it by hand?")#那就是:“什么,”你能用手做吗?
    

    代码运算

    "C:\Program Files\Python36\python.exe" "E:/学习/xiangmu/week two/ex21.py"
    Let's do some math with just functions!
    ADDING 30 + 5
    SUBTRACT 78 - 4
    MULTIPLY 90 * 2
    DIVID 100 / 2
    Age: 35, Height: 74, Weight: 180, IQ: 50
    Here is a puzzle.
    DIVID 50 / 2
    MULTIPLY 180 * 25
    SUBTRACT 74 - 4500
    ADDING 35 + -4426
    That becomes: -4391.0 Can you do it by hand?
    
    Process finished with exit code 0
    
    

    常见 问题回 答
    为什么 Python 会把函数或公式倒着打印出来?
    其实不是倒着打印,而是自内而外打印。如果你把函数内容逐句看下去,你会发现这里的规律。试
    着搞清楚为什么说它是“自内而外”而不是“自下而上”。
    怎样使用 raw_input() 输入自定义值?
    记得 int(raw_input()) 吧?不过这样也有一个问题,那就是你无法输入浮点数,所以你可
    以试着使用 float(raw_input()) 。
    你说的“写一个公式”是什么意思?
    来个简单的例子吧: 24 + 34 / 100 - 1023 —— 把它用函数的形式写出来。然后自己想
    一些数学式子,像公式一样用变量写出来。

    ex22

    平时的积累

    看见这道题目,好亲切,平时每个章节的练习,出了敲代码,我都有做纸质笔记,记录了很多符号的用途和单词的释义。

    ex23

    读代码的确蛮重要的,会去尝试读读另一本入门时的代码《简明python教程》和菜鸟网站的python教程。

    ex24

    #习题 24: 更多练习
    
    print("Let's  practice everyting.")
    print("You\'d need to know\ 'bout escapes with \\ that do \n newlines and \t tabs.")#你要知道\ '布特越狱\\\\做\\n换行和制表符
    
    poem = """
    \tThe lovely world
     with logic so firmly planted
     cannot discern \n the need of love
     nor comperhend passion form intuition
     and requires an an explanation
     \n\t\twhere there is none.
    """
    #可爱的世界 逻辑坚定 无法辨别爱的需要  也不是凭直觉理解激情  需要解释  \n\n T \那里有没有
    
    print("-------------")
    print(poem)
    print("-------------")
    
    five = 10 - 2 + 3 - 6
    print("This should be five: %s" % five)
    
    def secret_formula(started):
        jelly_beans = started * 500
        jars = jelly_beans / 1000
        crates = jars / 100
        return jelly_beans, jars, crates
    
    start_point = 10000
    beans, jars, crates = secret_formula(start_point)
    
    print("With a starting point of: %d" % start_point)#有一个起始点:%d
    print("We'd have %d beans, %d jars, and %d crates." % (beans, jars, crates))
    
    start_point = start_point / 10
    
    print("We can also do that this way:")#我们也可以这样做。
    print("We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point))
    

    运行结果

    "C:\Program Files\Python36\python.exe" "D:/小克学习/python/项目/week two/ex23.py"
    Let's  practice everyting.
    You'd need to know\ 'bout escapes with \ that do 
     newlines and    tabs.
    -------------
    
        The lovely world
     with logic so firmly planted
     cannot discern 
     the need of love
     nor comperhend passion form intuition
     and requires an an explanation
     
            where there is none.
    
    -------------
    This should be five: 5
    With a starting point of: 10000
    We'd have 5000000 beans, 5000 jars, and 50 crates.
    We can also do that this way:
    We'd have 500000 beans, 500 jars, and 5 crates.
    
    Process finished with exit code 0
    

    加分习题

    1. 记得仔细检查结果,从后往前倒着检查,把代码朗读出来,在不清楚的位置加上注释。
    2. 故意把代码改错,运行并检查会发生什么样的错误,并且确认你有能力改正这些错误。

    ex25

    代码

    def break_words(stuff):
        """This function is break up words for us."""#这个函数会为我们分解单词
        words = stuff.split(' ')
        return words
    
    def sort_words(words):
        """Sorts the words."""#各种各样的话
        return sorted(words)
    
    def print_first_word(words):
        """Prints the first word after poping it off."""#打印出第一个词后弹出
        word = words.pop(0)
        print(word)
    
    def print_last_word(words):
        """Prints the last word after poping it off."""#打印完最后一个字后弹出
        word = words.pop(-1)
        print(word)
    
    def sort_sentence(sentence):
        """Takes in a full sentence and returns the sorted words."""#接受一个完整的句子并返回已排序的单词
        words = break_words(sentence)
        return sort_words(words)
    
    def print_first_and_last(sentence):
        """Prints first and last words of the sentence."""#打印句子的第一个和最后一个单词
        words = break_words(sentence)
        print_first_word(words)
        print_last_word(words)
    
    def print_first_and_last_sorted(sentence):
        """Sorts the words then prints the first and last one."""#排序单词,然后打印第一个和最后一个。
        words = sort_sentence(sentence)
        print_first_word(words)
        print_last_word(words)
    
    
    CMD运行图

    ex26

    修改后的代码

    def break_words(stuff):
        """This function will break up words for us."""
        words = stuff.split(' ')
        return words
    
    def sort_words(words):
        """Sorts the words."""
        return sorted(words)
    
    def print_first_word(words):
        """Prints the first word after popping it off."""
        word = words.poop(0)
        print(word)
    
    def print_last_word(words):
        """Prints the last word after popping it off."""
        word = words.pop(-1)
        print(word)
    
    def sort_sentence(sentence):
        """Takes in a full sentence and returns the sorted words."""
        words = break_words(sentence)
        return sort_words(words)
    
    def print_first_and_last(sentence):
        """Prints the first and last words of the sentence."""
        words = break_words(sentence)
        print_first_word(words)
        print_last_word(words)
    
    def print_first_and_last_sorted(sentence):
        """Sorts the words then prints the first and last one."""
        words = sort_sentence(sentence)
        print_first_word(words)
        print_last_word(words)
    
    
    print ("Let's practice everything.")
    print ('You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.')
    
    poem = """
    \tThe lovely world
    with logic so firmly planted
    cannot discern \n the needs of love
    nor comprehend passion from intuition
    and requires an explantion
    \n\t\twhere there is none.
    """
    
    
    print ("--------------")
    print (poem)
    print ("--------------")
    
    five = 10 - 2 + 3 - 5
    print ("This should be five: %s" % five)
    
    def secret_formula(started):
        jelly_beans = started * 500
        jars = jelly_beans / 1000
        crates = jars / 100
        return jelly_beans, jars, crates
    
    
    start_point = 10000
    beans, jars, crates = secret_formula(start_point)
    
    print ("With a starting point of: %d" % start_point)
    print ("We'd have %d jeans, %d jars, and %d crates." % (beans, jars, crates))
    
    start_point = start_point / 10
    
    print ("We can also do that this way:")
    print ("We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point))
    
    
    sentence = "All god\tthings come to those who weight."
    
    words = ex25.break_words(sentence)
    sorted_words = ex25.sort_words(words)
    
    print_first_word(words)
    print_last_word(words)
    print_first_word(sorted_words)
    print_last_word(sorted_words)
    sorted_words = ex25.sort_sentence(sentence)
    print (sorted_words)
    
    print_irst_and_last(sentence)
    
    print_first_a_last_sorted(senence)
    
    

    运行结果

    "C:\Program Files\Python36\python.exe" "D:/小克学习/python/项目/week two/ex26.py"
    Traceback (most recent call last):
      File "D:/小克学习/python/项目/week two/ex26.py", line 79, in <module>
        words = ex25.break_words(sentence)
    NameError: name 'ex25' is not defined
    Let's practice everything.
    You'd need to know 'bout escapes with \ that do 
     newlines and    tabs.
    --------------
    
        The lovely world
    with logic so firmly planted
    cannot discern 
     the needs of love
    nor comprehend passion from intuition
    and requires an explantion
    
            where there is none.
    
    --------------
    This should be five: 6
    With a starting point of: 10000
    We'd have 5000000 jeans, 5000 jars, and 50 crates.
    We can also do that this way:
    We'd have 500000 beans, 500 jars, and 5 crabapples.
    
    Process finished with exit code 1
    
    

    总结:

    Traceback (most recent call last):
    File "D:/小克学习/python/项目/week two/ex26.py", line 79, in <module>
    words = ex25.break_words(sentence)
    NameError: name 'ex25' is not defined

    这个要import ex25了, 没有进行下去,其他的东西都修改过来了。

    相关文章

      网友评论

      本文标题:【Python爬虫】-第二周 习题 18-26

      本文链接:https://www.haomeiwen.com/subject/biejkxtx.html