【Python爬蟲作業(yè)】習題13-17

一,作業(yè)內容

笨辦法學Python習題13-17

二,作業(yè)代碼

習題13 參數(shù)灶挟、解包和變量

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)

應該看到的結果

The script is called: C:/Users/PycharmProjects/python3_project/ex13.py
Your first variable is: first
Your second variable is: 2nd
Your third variable is: 3rd

附加練習
1,給腳本3個以下的參數(shù)毒租,會得到錯誤信息稚铣。

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

因為我們設置的參數(shù)變量包括腳本本身是4個:script, first墅垮, second, third, 如果除了腳本少于3個惕医,程序會出錯。
2算色,
接受更少參數(shù)的腳本

from sys import argv

script, first, second = argv

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

結果是

The script is called: C:/Users/PycharmProjects/python3_project/ex13-1.py
Your first variable is: apple
Your second variable is: orange

接受更多參數(shù)的腳本

from sys import argv

script, first, second, third, fourth, fifth = 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)
print('Your third variable is:', fourth)
print('Your third variable is:', fifth)

結果是

The script is called: C:/Users/PycharmProjects/python3_project/ex13-2.py
Your first variable is: Learn
Your second variable is: Python
Your third variable is: the
Your third variable is: Hard
Your third variable is: Way

3抬伺,將input和argv一起使用

from sys import argv

script, first, second = argv
first = input("> ")
second = input("> ")

print('The script is called:', script)
print('Your first variable is: %s' % first)
print('Your second variable is: %s' % second)
> Hello
> Baby
The script is called: C:/Users/PycharmProjects/python3_project/ex13-3.py
Your first variable is: Hello
Your second variable is: Baby

4, 模塊需要導入(import),比如from sys import argv灾梦,把 sys模塊導入進來峡钓,模塊也稱為庫(library)妓笙。

習題13 心得體會:
一,在命令行中運行帶參數(shù)的腳本時能岩,可以直接把腳本名及其參數(shù)列上寞宫,如 python ex13.py first 2nd 3rd, 但是在Pycharm中運行腳本,需要設置腳本的參數(shù)拉鹃,在Run--Edit configurations... 中設置Script parameters.
二辈赋,參數(shù)是變量,與input函數(shù)一起使用時膏燕,在print模塊需要引用變量钥屈, %s % first

習題14 提示和傳遞

from sys import argv

script, user_name = argv
prompt = '> '

print('Hi %s, 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 = input(prompt)

print('Where do you live %s?' % user_name)
lives = input(prompt)

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

print('Alright, so you said %r about likeing me. '
      '\nYou live in %r. Not sure where that is. '
      '\nAnd you have a %r computer. Nice.' %(likes, lives, computer))

結果

Hi Faye, I'm the C:/Users/PycharmProjects/python3_project/ex14.py script.
I'd like to ask you a few questions.
Do you like me Faye
> Yes
Where do you live Faye?
> Beijing
What kind of computer do you have?
> Lenovo
Alright, so you said 'Yes' about likeing me. 
You live in 'Beijing'. Not sure where that is. 
And you have a 'Lenovo' computer. Nice.

附加練習
2,3題

from sys import argv

script, user_name, one_person  = argv
prompt = '~_~ '

print('Hi %s, 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 = input(prompt)

print('What a nice day, %s' % one_person)
one_person = input(prompt)

print('Where do you live %s?' % user_name)
lives = input(prompt)

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

print('Alright, so you said %r about likeing me. '
      '\nYou live in %r. Not sure where that is. '
      '\nAnd you have a %r computer. Nice.'
      '\nWhat a nice day, %s'%(likes, lives, computer, one_person))

習題15 讀取文件

from sys import argv  #從模塊sys導入?yún)?shù)argv

script, filename = argv # 參數(shù)包含script和filename

txt = open(filename) #txt方法是打開文件

print('Here\'s your file %r:' % filename) #打印“Here's your file ‘ex15_sample.txt’”
print(txt.read()) #print txt的文件內容

print('Type the filename again:') #打印'Type the filename again:'
file_again = input("> ") # 輸入文件名

txt_again = open(file_again) # 打開文件名

print(txt_again.read()) # 打印所輸入文件名的文件內容

應該看到的結果

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.

附加練習
5坝辫,用自定義輸入的方法獲取文件名稱更好篷就,這樣,這段代碼可以重復使用近忙,打開很多文件腻脏。
6

習題16 讀寫文件

from sys import argv #從sys模塊引入?yún)?shù)變量argv

script, filename = argv # 參數(shù)解包成script 和 filename

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. Goodbye!') #打印
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 going 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() # 關閉目標文件

應該看到的結果

We're going to erase 'test.txt'.
If you don't want that, hit CTRL-C(^C.)
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask you for three lines.
line 1: Mary had a little lamb
line 2: It's fleece was white as snow
line 3: It was also tasty
I'm going to write these to the file.
And finally, we close it.

附加練習
3银锻,

from sys import argv #從sys模塊引入?yún)?shù)變量argv

script, filename = argv # 參數(shù)解包成script 和 filename

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. Goodbye!') #打印
target.truncate() #清空目標文件

print('I\'m going to write these to the file.') # 打印

target.write('Mary had a little lamb \nIt\'s fleece was white as snow \nIt was also tasty')


print('And finally, we close it.')
target.close() # 關閉目標文件

4做鹰,給open賦予一個‘w’參數(shù)击纬,打開文件并且是寫入模式。

習題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 coud do these two on one line too, how?
in_file = open(from_file)
indata = in_file.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.')
input()

out_file = open(to_file, 'w')
out_file.write(indata)

print('Alright, all done')

out_file.close()
in_file.close()

應該看到的結果

Copying from cat.txt to test.txt
The input file is 25 bytes long
Does the output file exist? True
Ready, hit RETURN to continue, CTRL-C to abort.
yes
Alright, all done

附加練習
6钾麸,為什么需要在代碼中寫output.close()? 因為open函數(shù)的返回值是一個文件句柄更振, 這個句柄從操作系統(tǒng)托付給你的Python程序。一旦處理完文件饭尝,要歸還這個文件句柄肯腕,只有這樣程序不會超出一次能打開的文件句柄的數(shù)量上限。

心得:習題17的附加練習的題目還不理解钥平,需要繼續(xù)學習实撒。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市涉瘾,隨后出現(xiàn)的幾起案子知态,更是在濱河造成了極大的恐慌,老刑警劉巖立叛,帶你破解...
    沈念sama閱讀 206,126評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件负敏,死亡現(xiàn)場離奇詭異,居然都是意外死亡秘蛇,警方通過查閱死者的電腦和手機其做,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,254評論 2 382
  • 文/潘曉璐 我一進店門顶考,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人妖泄,你說我怎么就攤上這事驹沿。” “怎么了浮庐?”我有些...
    開封第一講書人閱讀 152,445評論 0 341
  • 文/不壞的土叔 我叫張陵甚负,是天一觀的道長。 經(jīng)常有香客問我审残,道長梭域,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,185評論 1 278
  • 正文 為了忘掉前任搅轿,我火速辦了婚禮病涨,結果婚禮上,老公的妹妹穿的比我還像新娘璧坟。我一直安慰自己既穆,他們只是感情好,可當我...
    茶點故事閱讀 64,178評論 5 371
  • 文/花漫 我一把揭開白布雀鹃。 她就那樣靜靜地躺著幻工,像睡著了一般。 火紅的嫁衣襯著肌膚如雪黎茎。 梳的紋絲不亂的頭發(fā)上囊颅,一...
    開封第一講書人閱讀 48,970評論 1 284
  • 那天,我揣著相機與錄音傅瞻,去河邊找鬼踢代。 笑死,一個胖子當著我的面吹牛嗅骄,可吹牛的內容都是我干的胳挎。 我是一名探鬼主播,決...
    沈念sama閱讀 38,276評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼溺森,長吁一口氣:“原來是場噩夢啊……” “哼慕爬!你這毒婦竟也來了?” 一聲冷哼從身側響起屏积,我...
    開封第一講書人閱讀 36,927評論 0 259
  • 序言:老撾萬榮一對情侶失蹤澡罚,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后肾请,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體留搔,經(jīng)...
    沈念sama閱讀 43,400評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 35,883評論 2 323
  • 正文 我和宋清朗相戀三年铛铁,在試婚紗的時候發(fā)現(xiàn)自己被綠了隔显。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片却妨。...
    茶點故事閱讀 37,997評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖括眠,靈堂內的尸體忽然破棺而出彪标,到底是詐尸還是另有隱情,我是刑警寧澤掷豺,帶...
    沈念sama閱讀 33,646評論 4 322
  • 正文 年R本政府宣布捞烟,位于F島的核電站,受9級特大地震影響当船,放射性物質發(fā)生泄漏题画。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,213評論 3 307
  • 文/蒙蒙 一德频、第九天 我趴在偏房一處隱蔽的房頂上張望苍息。 院中可真熱鬧,春花似錦壹置、人聲如沸竞思。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,204評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽盖喷。三九已至,卻和暖如春难咕,著一層夾襖步出監(jiān)牢的瞬間传蹈,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,423評論 1 260
  • 我被黑心中介騙來泰國打工步藕, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人挑格。 一個月前我還...
    沈念sama閱讀 45,423評論 2 352
  • 正文 我出身青樓咙冗,卻偏偏與公主長得像,于是被迫代替她去往敵國和親漂彤。 傳聞我的和親對象是個殘疾皇子雾消,可洞房花燭夜當晚...
    茶點故事閱讀 42,722評論 2 345

推薦閱讀更多精彩內容

  • Ubuntu的發(fā)音 Ubuntu媳板,源于非洲祖魯人和科薩人的語言桑腮,發(fā)作 oo-boon-too 的音。了解發(fā)音是有意...
    螢火蟲de夢閱讀 99,156評論 9 467
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理蛉幸,服務發(fā)現(xiàn)破讨,斷路器丛晦,智...
    卡卡羅2017閱讀 134,599評論 18 139
  • 習題0:準備工作 總有一天你會聽到有程序員建議你使用 Mac OSX 或者 Linux。如果他喜歡字體美觀提陶,他會告...
    KennyP0618閱讀 2,202評論 0 1
  • 今天烫沙,又是11月,倒數(shù)第二天了隙笆。 這是我出來畢業(yè)實習以后第一次锌蓄,跳出這個地方,第一次走在大街上的時候撑柔,那種孤獨瘸爽,是...
    熊芳菲閱讀 154評論 0 0
  • 菲利普曲線的移動。短期菲利普曲線是斜向下的乏冀。因為失業(yè)率高蝶糯,那么政府在減少貨幣供給;長期菲利普曲線的失業(yè)率就是一根線...
    sunflower_d66c閱讀 120評論 0 0