2016.8.18 Automate the boring stuff with python學(xué)習(xí)總結(jié)

今天突然在網(wǎng)上看到了這本電子pdf褂始,看見還有視頻課程携悯,不過課程貌似收費(fèi)计贰,心想著Python一直沒怎么學(xué),也沒怎么用它來編程拯钻,今天趁著有空學(xué)一下吧。

首先瀏覽了一下目錄撰豺,有幾章還是挺感興趣的粪般,像 **chapter8 reading and writing files, chapter 10 debugging , chapter 11 web scraping. **

抱著想要看看這本書質(zhì)量怎么樣的心態(tài),看了這本書看我能學(xué)到多少東西污桦,查漏補(bǔ)缺亩歹,因?yàn)楝F(xiàn)在自己的python水平完全是菜鳥級(jí)別。凡橱。小作。等看完了,最后再評(píng)價(jià)這本書稼钩。

都說興趣是最好的老師顾稀,只有抱著一種想要探索,想要把這個(gè)搞懂的心態(tài)坝撑,才能真正的學(xué)進(jìn)去静秆。**PS:只有當(dāng)你對(duì)一個(gè)東西不感興趣時(shí),你才會(huì)使勁逼迫著自己去做這件事巡李。如果你很喜歡抚笔,根本不需要所謂的自我約束,興趣會(huì)驅(qū)動(dòng)著你前行击儡。**

If you can’t? nd the answer by searching online, try asking people in aweb forum such as Stack Overlow (http://stackover ow.com/) or the “l(fā)earnprogramming” subreddit at http://reddit.com/r/learnprogramming/.

一些操作符塔沃,'//' 原來不知道是什么意思,現(xiàn)在知道了

operator

\d 數(shù)字,\w 單詞蛀柴,字符串螃概,\s 空格

codes

原來查linux的時(shí)候看到過這些正則表達(dá)式分別是什么,現(xiàn)在終于記住了鸽疾。吊洼。。

PS:由此可見制肮,自己的記性是有多差冒窍。。豺鼻。

`

#manipulate strings

print('Hello there!\nHow are you?\nI\'m doing fine.')

#raw string

print(r'That is Carol\'s cat.')

#

spam='appLe'

spam.lower()

'hello'.isalpha()

'hello123'.isalnum()

'123'.isdecimal()

' '.isspace()

'Hello world!'.startswith('Hello')

' '.join(spam)

spam=' Hello World'

spam.strip()

spam.lstrip()

spam.rstrip()

import pyperclip

text = pyperclip.paste()

# Separate lines and add stars.

lines = text.split('\n')

for i in range(len(lines)):# loop through all indexes in the "lines" list

lines[i] = '* ' + lines[i] # add star to each string in "lines" list

pyperclip.copy(text)

pyperclip.copy()

pyperclip.paste()

#All the regex functions in Python are in the re module

import re

# re.compile() returns a Regex pattern object

phonenumber=re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')

mo=phonenumber.search('my number is 150-021-18276')

print('phone number is found :'+mo.group())

mo.group(1)

mo.group(2)

mo.group(0)

mo.group()

mo.groups()

'''

1. Import the regex module with import re.

2. Create a Regex object with the re.compile() function.

(Remember to use a

raw string.)

3. Pass the string you want to search into the Regex object’s search() method.

This returns a Match object.

4. Call the Match object’s group() method to return a string of the actual

matched text.

'''

phonenumber.findall('cell:415-555-9999 work: 212-555-0000')

######

import os

os.getcwd()

os.chdir("/Users/apple")

os.makedirs('/Users/apple/python')

os.path.abspath('.')

totalSize=0

for filename in os.listdir('/Users/apple'):

toralSize+=os.path.getsize('/Users/apple',filename)

print(totalSize)

os.path.exists('/Users/apple')

os.path.isdir('/Users/apple')

os.path.isfile('/Users/apple')

#the shutil module

#The shutil (or shell utilities) module has functions to let you copy,

#move, rename, and delete? les in your Python programs.

import shutil,os

shutil.copy('apple.txt','test.txt')

shutil.copytree('C:\\bacon', 'C:\\bacon_backup')#shutil.copytree() will copy an entire folder and every folder and? le contained in it.

shutil.move('C:\\bacon.txt', 'C:\\eggs')

os.unlink(path) #will delete the? le at path.

os.rmdir(path)#will delete the folder at path. This folder must be

empty of any? les or folders.

shutil.rmtree(path)#will remove the folder at path, and all? les and folders it contains will also be deleted.

import os

for filename in os.listdir():

if filename.endswith('.rxt'):

os.unlink(filename)

import os

for filename in os.listdir():

if filename.endswith('.rxt'):

#os.unlink(filename)

print(filename)

#A much better way to delete? les and folders is with the third-party send2trash module.

send2trash.send2trash('bacon.txt')

os.walk()

#Reading ZIP Files

import zipfile, os

exampleZip = zipfile.ZipFile('example.zip')

exampleZip.namelist()

spamInfo = exampleZip.getinfo('spam.txt')

spamInfo.compress_size

exampleZip.close()

#Extracting from ZIP Files

exampleZip.extractall()

exampleZip.close()

exampleZip.extract('spam.txt', 'C:\\some\\new\\folders')

backupZip = zipfile.ZipFile(zipFilename, 'w')

#raising exceptions

import traceback

try:

raise Exception('This is the error information.')

except:

errorFile=open('errorInfo.txt','w')

errorFile.write(traceback.format_exc())

errorFile.close()

print('The traceback info was written to errorInfo.txt')

#An assertion is a sanity check to make sure your code isn’t doing something obviously wrong.

import logging

logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')

logging.debug()

logging.info()

logging.warning()

logging.error()

logging.critical()

logging.basicConfig(filename='myProgramLog.txt', level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')

import webbrowser

webbrowser.open('http://inventwithpython.com')

import requests

res=requests.get('http://www.gutenberg.org/cache/epub/1112/pg1112.txt')

try:

res.raise_for_status()

except Exception as exc:

print('There was a problem:%s' % (exc))

type(res)

res.status_code==resquests.codes.ok

len(res.text)

print(res.text(:250))

playFile = open('RomeoAndJuliet.txt', 'wb')

for chunk in res.iter_content(100000):

playFile.write(chunk)

playFile.close()

`

###############file() 函數(shù)

file()函數(shù)是2.2中新增的函數(shù)综液,它與open()函數(shù)一樣,相當(dāng)于open()的別名儒飒,不過比open()更直觀一些谬莹。

for line in file(filename):

print line

[#######對(duì)于為什么要用__name__='__main__'? 參見文章:](http://www.crifan.com/python_detailed_explain_about___name___and___main__/)

寫的很詳細(xì)。一下就看懂了桩了。

對(duì)于sys.argv 的用法參見文章:[sys.argv](http://blog.csdn.net/vivilorne/article/details/3863545)

寫的很詳細(xì)附帽,學(xué)習(xí)了。把程序看懂井誉,自己寫一遍蕉扮。

#Debugging

為了防止程序crash,可以把traceback information 寫到log file里颗圣。

**Web Scrapping"

*webbrowser* :Comes with Python and opens a browser to a specific page.

*Requests*: Downloads? les and web pages from the Internet.

*Beautiful Soup*: ?Parses HTML, the format that web pages are written in.

*Selenium*: Launches and controls a web browser. Selenium is able to ll in forms and simulate mouse clicks in this browser.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末喳钟,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子欠啤,更是在濱河造成了極大的恐慌荚藻,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,627評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件洁段,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡共郭,警方通過查閱死者的電腦和手機(jī)祠丝,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,180評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來除嘹,“玉大人写半,你說我怎么就攤上這事∥竟荆” “怎么了叠蝇?”我有些...
    開封第一講書人閱讀 169,346評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)年缎。 經(jīng)常有香客問我悔捶,道長(zhǎng)铃慷,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,097評(píng)論 1 300
  • 正文 為了忘掉前任蜕该,我火速辦了婚禮犁柜,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘堂淡。我一直安慰自己馋缅,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,100評(píng)論 6 398
  • 文/花漫 我一把揭開白布绢淀。 她就那樣靜靜地躺著萤悴,像睡著了一般。 火紅的嫁衣襯著肌膚如雪皆的。 梳的紋絲不亂的頭發(fā)上稚疹,一...
    開封第一講書人閱讀 52,696評(píng)論 1 312
  • 那天,我揣著相機(jī)與錄音祭务,去河邊找鬼内狗。 笑死,一個(gè)胖子當(dāng)著我的面吹牛义锥,可吹牛的內(nèi)容都是我干的柳沙。 我是一名探鬼主播,決...
    沈念sama閱讀 41,165評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼拌倍,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼赂鲤!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起柱恤,我...
    開封第一講書人閱讀 40,108評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤数初,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后梗顺,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體泡孩,經(jīng)...
    沈念sama閱讀 46,646評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,709評(píng)論 3 342
  • 正文 我和宋清朗相戀三年寺谤,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了仑鸥。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,861評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡变屁,死狀恐怖眼俊,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情粟关,我是刑警寧澤疮胖,帶...
    沈念sama閱讀 36,527評(píng)論 5 351
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響澎灸,放射性物質(zhì)發(fā)生泄漏院塞。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,196評(píng)論 3 336
  • 文/蒙蒙 一击孩、第九天 我趴在偏房一處隱蔽的房頂上張望迫悠。 院中可真熱鬧,春花似錦巩梢、人聲如沸创泄。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,698評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽鞠抑。三九已至,卻和暖如春忌警,著一層夾襖步出監(jiān)牢的瞬間搁拙,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,804評(píng)論 1 274
  • 我被黑心中介騙來泰國(guó)打工法绵, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留箕速,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,287評(píng)論 3 379
  • 正文 我出身青樓朋譬,卻偏偏與公主長(zhǎng)得像盐茎,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子徙赢,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,860評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容