【Python爬虫作业】习题18-26

一. 作业内容

笨办法学Python习题18-26

二. 作业代码

习题18

# this one is like your scripts 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 nothing.')


print_two('Zed', 'Shaw')
print_two_again('Zed', 'Shaw')
print_one('First')
print_none()

应该看到的结果

arg1: 'Zed', arg2: 'Shaw'
arg1: 'Zed', arg2: 'Shaw'
arg1:'First'
I got nothing.

附加练习
函数定义以def开始,和变量名一样,只要以字母,数字以及下划线组成,而且不是数字开始,就可以了。函数名紧跟着括号(,括号里可以包括参数,也可以不包括参数。多个参数以逗号隔开。参数名称不能重复。紧跟着的参数的是括号和冒号 ():)。紧跟着函数定义的代码要使用4个空格的缩进。函数结束的位置取消了缩进。

运行一个函数时,要检查以下要点:

  1. 调用函数时是否使用了函数名。
  2. 函数名是否紧跟着(。
  3. 括号后有无参数, 多个参数是否以逗号隔开。
  4. 函数是否以)结尾。

心得体会:

对于函数的名称,要避开python内置的关键词。获得python关键词的方法是

import keyword
print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

习题19

def cheese_and_crackers(cheese_count, boxes_of_crackers):  #定义一个函数,内含2个参数
    print('You have %d cheeses!' % 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 function 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) # 给函数传递数学表达式和变量

应该看到的结果

We can just give the function numbers directly:
You have 20 cheeses!
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 cheeses!
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 cheeses!
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 cheeses!
You have 1050 boxes of crackers!
Man that's enough for a party
Get a blanket.

附加练习
3 编写一个函数

def python_homework(complete_date, complete_quality):
    print('I do the homework on %s and complete it %s at last' %(complete_date, complete_quality))


python_homework('21-JUL-2017', 'very good')

date_one = '22-JUL-2017'
quality_one = 'bad'
python_homework(date_one, quality_one)

print('please enter a date for the python homework you do')
date_one = input('> ')
print('please enter the quality for the python homework you do')
quality_one = input('> ')
python_homework(date_one, quality_one)
I do the homework on 21-JUL-2017 and complete it very good at last
I do the homework on 22-JUL-2017 and complete it bad at last
please enter a date for the python homework you do
> 20-JUN-2017
please enter the quality for the python homework you do
> VERY GOOD
I do the homework on 20-JUN-2017 and complete it VERY GOOD at last

心得体会: int() 把input()的值转化为整数。不可以把全局变量的名称和函数变量的名称取成一样的。

习题20 函数和文件

from sys import argv #从sys模块导入参数argv

script, input_file = argv #把参数argv解包成两个参数:script和input_file

def print_all(f):  #定义一个函数 print_all(), 传递的参数是f
    print(f.read()) #打印f的内容

def rewind(f): #定义一个函数rewind, 传递的参数是f
    f.seek(0) # 从文件f的开始位置读起

def print_a_line(line_count, f): #定义一个函数print_a_line, 传递的参数是line_count 和f
    print (line_count, f.readline()) # 打印line_count, 读取文件f当前行

current_file = open(input_file) # 打开所输入的文件, 把这个方法赋值给变量current_file

print('First let\'s print the whole file:\n') # 打印

print_all(current_file) #读取代开文件的所有行

print('Now let\'s rewind, kind of like a tape') # 打印

rewind(current_file) #从当前文件的起始位置读起

print('Let\'s print three lines:') #打印

current_line = 1 #把1赋值给current_line
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)

应该看到的结果

First let's print the whole file:

Lear
Python
the 
hard
way
Now let's rewind, kind of like a tape
Let's print three lines:
1 Lear

2 Python

3 the 

附加练习:

  1. file中的seek函数是读取位置, seek(0)代表从起始位置读起,seek(1) 从当前位置读起,seek(2) 从末尾位置读起。 tell(): 文件的当前位置,即tell是获得文件指针位置。readline(n):读入若干行,n表示读入的最长字节数。其中读取的开始位置为tell()+1。当n为空时,默认只读当前行的内容。readlines读入所有行内容,read读入所有行内容。
  2. 操作符 +=, 例如x+=1表示 x=x+1

习题21 函数可以返回某些东西

def add(a, b):
    print('Adding %d + %d' %(a, b))
    return a + b

def substract(a, b):
    print('SUBTRACTING %d - %d' %(a, b))
    return a - b

def multiply(a, b):
    print('MULTIPLYING %d * %d' %(a, b))
    return a * b

def divided(a, b):
    print('DIVIDING %d / %d' % (a, b))
    return a / b


print('Let\'s do some math with just functions!')

age = add(30, 5)
height = substract(78, 4)
weight = multiply(90, 2)
iq = divided(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, substract(height, multiply(weight, divided(iq, 2))))

print('That becomes:', what, 'Can you do it by hand?')

应该看到的结果

Let's do some math with just functions!
Adding 30 + 5
SUBTRACTING 78 - 4
MULTIPLYING 90 * 2
DIVIDING 100 / 2
Age: 35, Height: 74, Weight: 180, IQ: 50
Here is a puzzle.
DIVIDING 50 / 2
MULTIPLYING 180 * 25
SUBTRACTING 74 - 4500
Adding 35 + -4426
That becomes: -4391.0 Can you do it by hand?

附加练习

def add(a, b):
    print('Adding %d + %d' % (a, b))
    return a + b

age = add(30, 5)
print('Age: %d' %(age))

结果

Adding 30 + 5
Age: 35

习题24 更多练习

print('Let\'s practice everything.')
print('You\'d need to known\'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 requireds an explanation
\n\t\twhere there is none.
'''

print('-----------------')
print(poem)
print('-----------------')


five = 10 - 2 + 3 - 6
print('This should be five: %s' % five)

def secret_formula(started): # 定义一个函数,其参数为started
    jelly_beans = started * 500 # 把参数started × 500赋值给变量jelly_beans
    jars = jelly_beans / 1000  # 把jelly_beans/1000 赋值给jars
    crates =jars / 100 #把 jars/100 赋值给crates
    return jelly_beans, jars, crates #返回jelly_beans, jars, crates


start_point = 10000 #把10000赋值给变量start_point
beans, jars, crates = secret_formula(start_point) # 把变量作为参数,放入函数中,得到函数的三个变量
print('With a starting point of: %d' % start_point)

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))

应该看到的结果

Let's practice everything.
You'd need to known'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 requireds 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.

心得体会:
python3中 print‘’‘ ’‘’相当于python2 中的 “”“ ”“”,可以引用一段话
return表示返回函数的值

习题25 更多更多的实践

def break_words(stuff):
    '''This function will break up words for us.'''
    words = stuff. split(' ')
    return words

#sentence = "I am writing python."
#b = break_words(sentence)
#print(b)

def sort_words(words):
    return sorted(words)
#sentence1 = "i am writing python"
#a = sort_words(sentence)
#print(a)

def print_first_word(words):
    word = words.pop(0)
    print(word)

def print_last_word(words):
    word = words.pop(-1)
    print(word)

def sort_sentence(sentence):
    words = break_words(sentence)
    return sort_words(words)

def print_first_and_last(sentence):
    words = break_words(sentence)
    print_first_word(words)
    print_last_word(words)

def print_first_and_last_sorted(sentence):
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)

image.png

附加练习
2,执行help(ex25)和help(ex25.break_words)

image.png

心得体会:
习题25的函数需要在命令行的python的交互模式下进行, 即先cd ex25.py所在的路径, 进入python,再import ex25,即可让程序运行下去。

"""This function will break up words for us.""" 这是函数的帮助文档。

习题26 考试

修改后的代码如下

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.pop(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_sentence(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."

from ex25 import *
words = break_words(sentence)
sorted_words = sort_words(words)

print_first_word(words)
print_last_word(words)
print_first_word(sorted_words)
print_last_word(sorted_words)
sorted_words = sort_sentence(sentence)
print (sorted_words)

print_first_and_last(sentence)

print_first_and_last_sorted(sentence)

运行结果如下:

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.
All
weight.
All
who
['All', 'come', 'god\tthings', 'those', 'to', 'weight.', 'who']
All
weight.
All
who

心得体会:
移除import ex25.py, 那部分关于ex25的代码将不会运行。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,719评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,337评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,887评论 0 324
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,488评论 1 266
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,313评论 4 357
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,284评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,672评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,346评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,644评论 1 293
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,700评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,457评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,316评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,706评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,990评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,261评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,648评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,859评论 2 335

推荐阅读更多精彩内容