【Python爬虫】-笨办法学 Python 习题13-17

一、作业内容

笨办法学 Python 习题13-17以及加分题。

二、作业代码:

# 习题 13:参数、解包、变量
from sys import argv

script, first, second, third = argv

print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)

运行结果如下:

Traceback (most recent call last):
  File "E:/python3_project/ex13.py", line 4, in <module>
    script, first, second, third = argv
ValueError: not enough values to unpack (expected 4, got 1)

Process finished with exit code 1

结果却报错……
读一下第四行的报错信息:
ValueError: not enough values to unpack (expected 4, got 1)
意思就是:没有足够的值来解包(期望4,得到1)
在群里查看了一下聊天记录,这道题需要在命令行中运行:
若在命令行中运行.py的文件,输入的字符一个都不能出错,

  1. 首先输入cmd打开命令行窗口
  2. cd命令来改变目录到我保存文件的地方。
  3. 运行.py文件。而且需要输入变量名,否则会报错。

命令行运行结果如下:

C:\Users\henan>cd /d e:\python3_project
e:\python3_project>python ex13.py 1 2 3
The script is called: ex13.py
Your first variable is: 1
Your second variable is: 2
Your third variable is: 3

分别将参数first, second, third 修改为cheese apples bread
命令行运行结果如下:

e:\python3_project>python ex13.py cheese apples bread
The script is called: ex13.py
Your first variable is: cheese
Your second variable is: apples
Your third variable is: bread

搞定!不过似乎文件名也算是一个值?

# 加分习题
# 一、给你的脚本三个以下的参数。看看会得到什么错误信息。试着解释一下。
e:\python3_project>python ex13.py cheese apples
Traceback (most recent call last):
  File "ex13.py", line 4, in <module>
    script, cheese, apples, bread = argv
ValueError: not enough values to unpack (expected 4, got 3)
# 没有足够的值来解包。
# 二、再写两个脚本,其中一个接受更少的参数,另一个接受更多的参数,在参数解包时给它们取一些有意义的变量名。
# 三、将 raw_input 和 argv 一起使用,让你的脚本从用户手上得到更多的输入。
# 四、记住“模组(modules)”为你提供额外功能。多读几遍把这个词记住,因为我们后面还会用到它。
# 习题14:提示和传递
from sys import argv

script, user_name = argv
prompt = '> '

print("Hi %r, I'm the %s script." % (user_name, script))
print("I'd like to ask you a few questions.")
print("Do you like me %s?" % user_name)
# 将 likes = raw_input(prompt) 中的 raw_input改为input
likes = input(prompt)

print("Where do you live %s?" % user_name)
# 同上,将 raw_input改为input
lives = input(prompt)

print("What kind of computer do you have?")
computer = input(prompt)

print("""
Alright, so you said %r about liking me.
You live in %r. Not sure where that is.
And you have a %r computer.
""" % (likes, lives, computer))

命令行的运行结果如下:

e:\python3_project>python ex14.py user_name
Hi 'user_name', I'm the ex14.py script.
I'd like to ask you a few questions.
Do you like me user_name?
> yes
Where do you live user_name?
> China
What kind of computer do you have?
> Zed

Alright, so you said 'yes' about liking me.
You live in 'China'. Not sure where that is.
And you have a 'Zed' computer.
# 加分习题
# 一、查一下 Zork 和 Adventure 是两个怎样的游戏。 看看能不能下载到一版,然后玩玩看。
# 二、将 prompt 变量改成完全不同的内容再运行一遍。
# 三、给你的脚本再添加一个参数,让你的程序用到这个参数。
# 四、确认你弄懂了三个引号 """ 可以定义多行字符串,而 % 是字符串的格式化工具。
# 习题15:读取文件
from sys import argv

script, filename = argv

txt = open(filename)

print("Here's your file %r:" % filename)
print(txt.read())

print("Type the filename again:")
file_again = input("> ")

txt_again = open(file_again)

print(txt_again.read())

并在文件目录创建一个名为ex15_sample.txt的文本。
文本内容如下:

This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

使用命令行运行结果如下:

e:\python3_project>python ex15.py ex15_sample.txt
Here's your file 'ex15_sample.txt':
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

Type the filename again:
> ex15_sample.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

# 习题 16: 读写文件
from sys import argv

script, filename = argv

print("We're going to erase %r." % filename)
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.")

input("?")

print("Opening the file...")
target = open(filename, 'w')

print("Truncating the file.  Gooodbye!")
target.truncate()

print("Now I'm going to ask you for three lines.")

line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")

print("I'm goin to write these to the file.")

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print("And finally, we close it.")
target.close()

使用命令行运行结果如下:

e:\python3_project>python ex16.py filename
We're going to erase 'filename'.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file.  Gooodbye!
Now I'm going to ask you for three lines.
line 1: To all the people out there.
line 2: I say I don't like my hair.
line 3: I need to share it off.
I'm goin to write these to the file.
And finally, we close it.

e:\python3_project>python ex16.py filename
We're going to erase 'filename'.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?Traceback (most recent call last):
  File "ex16.py", line 9, in <module>
    input("?")
KeyboardInterrupt

e:\python3_project>python ex16.py Ubuayyyy
We're going to erase 'Ubuayyyy'.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file.  Gooodbye!
Now I'm going to ask you for three lines.
line 1: You!
line 2: YOU!
line 3: ...
I'm goin to write these to the file.
And finally, we close it.
  1. 在命令行运行的第一段结果是,我按照提示敲下回车键,随后输入文本第一行、第二行和第三行的内容,最后创建出名为 filename 的文本。
  2. 在命令行运行的第二段结果是,我按照提示敲下CTRL-C,删除了文件名为 filename 的文本。
  3. 在第三次运行时,我在输入ex16.py后输入的第二个变量是 Ubuayyyy,这将修改要创建的默认文件名称。随后按照提示敲下回车键,并输入文本第一行、第二行和第三行的内容,最后创建出名 Ubuayyyy 的文本。
# 习题 17: 更多文件操作
from sys import argv
from os.path import exists

script, from_file, to_file = argv

print("Copying from %s to %s" % (from_file, to_file))

# we could do these two on one line too, how?
input = open(from_file)
indata = input.read()

print("The input file is %d bytes long" % len(indata))

print("Does the output file exist? %r" % exists(to_file))
print("Ready, hit RETURN to continue, CTRL-C to abort.")
# raw_input() 这句会导致报错,被我注释掉了

output = open(to_file, "w")
output.write(indata)

print("Alright, all done.")

output.close()
input.close()

命令行运行结果如下:

e:\python3_project>python ex17.py filename.txt copied.txt
Copying from filename.txt to copied.txt
The input file is 81 bytes long
Does the output file exist? False
Ready, hit RETURN to continue, CTRL-C to abort.
Alright, all done.

raw_input() 会导致报错……所以我把它注释了一下,如果保留并在命令行中运行,结果如下:

e:\python3_project>python ex17.py filename.txt copied.txt
Copying from filename.txt to copied.txt
The input file is 81 bytes long
Does the output file exist? True
Ready, hit RETURN to continue, CTRL-C to abort.
Traceback (most recent call last):
  File "ex17.py", line 17, in <module>
    input()
TypeError: '_io.TextIOWrapper' object is not callable

三、学习总结

总结中,迟些时候再补上(好吧,已经是第三次这么说了,不要打我)。
一定在这周补上。

推荐阅读更多精彩内容