1、 5//2=2
5/2=2.5
2、全局變量 global foo
3、list.index(xx) 沒有則引發(fā)異常
append,insert(x),remove()
self.sort(reverse=True) self.sort(key=str.lower)
sorted
4
type(('hello',))
<class 'tuple'>
type(('hello'))
<class 'str'>
5list ~ tuple
6、copy.copy 復制值而已
import copy
spam = ['A', 'B', 'C', 'D']
cheese = copy.copy(spam)
cheese[1] = 42
spam
['A', 'B', 'C', 'D']
cheese
['A', 42, 'C', 'D']
7、dict.get('key1',0)
8 string
upper,lower,isupper,islower,,isalpha,isalnum,isdecimal,isspace,startswith,endswith,
join,split(),rjust,ljust
'Hello'.rjust(10)
' Hello'
'Hello'.rjust(20)
'
Hello'
'Hello World'.rjust(20)
' Hello World'
'Hello'.ljust(10)
'Hello '
'Hello'.rjust(20, '')
'***************Hello'
'Hello'.ljust(20, '-')
'Hello---------------'
'Hello'.center(20)
' Hello '
'Hello'.center(20, '=')
'=======Hello========'
'start'.center(20,'')
spam = ' Hello World '
spam.strip()
'Hello World'
spam.lstrip()
'Hello World '
spam.rstrip()
' Hello World'
9 貪婪模式和非貪婪模式
nongreedyRegex = re.compile(r'<.?>')
mo = nongreedyRegex.search('<To serve man> for dinner.>')
mo.group()
'<To serve man>'
greedyRegex = re.compile(r'<.>')
mo = greedyRegex.search('<To serve man> for dinner.>')
mo.group()
'<To serve man> for dinner.>'
包括換行符:re.DOTALL
noNewlineRegex = re.compile('.')
noNewlineRegex.search('Serve the public trust.\nProtect the innocent.
\nUphold the law.').group()
'Serve the public trust.'
newlineRegex = re.compile('.', re.DOTALL)
newlineRegex.search('Serve the public trust.\nProtect the innocent.\nUphold the law.').group()cheese = copy.copy(spam)
>>> cheese[1] = 42
>>> spam
['A', 'B', 'C', 'D']
>>> cheese
['A', 42, 'C', 'D']
7、dict.get('key1',0)
8 string
upper,lower,isupper,islower,,isalpha,isalnum,isdecimal,isspace,startswith,endswith,
join,split(),rjust,ljust
>>> 'Hello'.rjust(10)
' Hello'
>>> 'Hello'.rjust(20)
'
Hello'
>>> 'Hello World'.rjust(20)
' Hello World'
>>> 'Hello'.ljust(10)
'Hello '
>>> 'Hello'.rjust(20, '')
'***************Hello'
>>> 'Hello'.ljust(20, '-')
'Hello---------------'
>>> 'Hello'.center(20)
' Hello '
>>> 'Hello'.center(20, '=')
'=======Hello========'
'start'.center(20,'')
>>> spam = ' Hello World '
>>> spam.strip()
'Hello World'
>>> spam.lstrip()
'Hello World '
>>> spam.rstrip()
' Hello World'
9 貪婪模式和非貪婪模式
>>> nongreedyRegex = re.compile(r'<.?>')
>>> mo = nongreedyRegex.search('<To serve man> for dinner.>')
>>> mo.group()
'<To serve man>'
>>> greedyRegex = re.compile(r'<.>')
>>> mo = greedyRegex.search('<To serve man> for dinner.>')
>>> mo.group()
'<To serve man> for dinner.>'
包括換行符:re.DOTALL
>>> noNewlineRegex = re.compile('.')
>>> noNewlineRegex.search('Serve the public trust.\nProtect the innocent.
\nUphold the law.').group()
'Serve the public trust.'
>>> newlineRegex = re.compile('.', re.DOTALL)
>>> newlineRegex.search('Serve the public trust.\nProtect the innocent.\nUphold the law.').group()
'Serve the public trust.\nProtect the innocent.\nUphold the law.'
不區(qū)分大小寫:re.I, re.IGNORECASE
sub替換字符串
namesRegex = re.compile(r'Agent \w+')
namesRegex.sub('CENSORED', 'Agent Alice gave the secret documents to Agent Bob.')
'CENSORED gave the secret documents to CENSORED.'
忽略空白符和注釋:re.VERBOSE
組合使用:someRegexValue = re.compile('foo', re.IGNORECASE | re.DOTALL | re.VERBOSE)
10文檔路徑:
import os
os.path.join('a','b','c')
myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
for filename in myFiles:'Hello'.center(20, '=')
'=======Hello========'
'start'.center(20,'')
>>> spam = ' Hello World '
>>> spam.strip()
'Hello World'
>>> spam.lstrip()
'Hello World '
>>> spam.rstrip()
' Hello World'
9 貪婪模式和非貪婪模式
>>> nongreedyRegex = re.compile(r'<.?>')
>>> mo = nongreedyRegex.search('<To serve man> for dinner.>')
>>> mo.group()
'<To serve man>'
>>> greedyRegex = re.compile(r'<.>')
>>> mo = greedyRegex.search('<To serve man> for dinner.>')
>>> mo.group()
'<To serve man> for dinner.>'
包括換行符:re.DOTALL
>>> noNewlineRegex = re.compile('.')
>>> noNewlineRegex.search('Serve the public trust.\nProtect the innocent.
\nUphold the law.').group()
'Serve the public trust.'
>>> newlineRegex = re.compile('.*', re.DOTALL)
>>> newlineRegex.search('Serve the public trust.\nProtect the innocent.\nUphold the law.').group()
'Serve the public trust.\nProtect the innocent.\nUphold the law.'
不區(qū)分大小寫:re.I, re.IGNORECASE
sub替換字符串
>>> namesRegex = re.compile(r'Agent \w+')
>>> namesRegex.sub('CENSORED', 'Agent Alice gave the secret documents to Agent Bob.')
'CENSORED gave the secret documents to CENSORED.'
忽略空白符和注釋:re.VERBOSE
組合使用:someRegexValue = re.compile('foo', re.IGNORECASE | re.DOTALL | re.VERBOSE)
10文檔路徑:
import os
os.path.join('a','b','c')
>>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx']
>>> for filename in myFiles:
print(os.path.join('C:\Users\asweigart', filename))
C:\Users\asweigart\accounts.txt
C:\Users\asweigart\details.csv
C:\Users\asweigart\invite.docx
os.getcwd()
os.chdir()
os.makedirs()
os.path.abspath('.')
os.path.basename()
os.path.dirname()
calcFilePath.split(os.path.sep)
['C:', 'Windows', 'System32', 'calc.exe']
'/usr/bin'.split(os.path.sep)
['', 'usr', 'bin']
os.path.getsize()
os.listdir()
os.path.exists()
os.path.isdir
os.path.isfile
open().read
open().readlines()
11 shutil
shutil.copy(xx,dir)
import shutil, os
os.chdir('C:\')
? >>> shutil.copy('C:\spam.txt', 'C:\delicious')
'C:\delicious\spam.txt'
? >>> shutil.copy('eggs.txt', 'C:\delicious\eggs2.txt')
' C:\delicious\eggs2.txt'
shutil.copytree(dir1,dir2) dir2文件夾復制dir1
shutil.move(file1,dir1) 移動
shutil.move(file1,file2) 改名
os.unlink() 刪除文件
shutil.rmtree 刪除文件夾
? 用os.unlink(path)將刪除path 處的文件。
? 調用os.rmdir(path)將刪除path 處的文件夾。該文件夾必須為空,其中沒有任
何文件和文件夾。
? 調用shutil.rmtree(path)將刪除path 處的文件夾,它包含的所有文件和文件夾都
會被刪除。
for dirname,subdirnames,filenames in os.walk(xx)
12 zipfile
import zipfile, os
os.chdir('C:\') # move to the folder with example.zip
exampleZip = zipfile.ZipFile('example.zip')
exampleZip.namelist()
['spam.txt', 'cats/', 'cats/catnames.txt', 'cats/zophie.jpg']
spamInfo = exampleZip.getinfo('spam.txt')
spamInfo.file_size
13908
spamInfo.compress_size
3828
? >>> 'Compressed file is %sx smaller!' % (round(spamInfo.file_size / spamInfo
.compress_size, 2))
'Compressed file is 3.63x smaller!'
exampleZip.close()
解壓
import zipfile, os
os.chdir('C:\') # move to the folder with example.zip
exampleZip = zipfile.ZipFile('example.zip')
? >>> exampleZip.extractall()
exampleZip.close()
單獨解壓
exampleZip.extract('spam.txt')
'C:\spam.txt'
exampleZip.extract('spam.txt', 'C:\some\new\folders')
import shutil, os
>>> os.chdir('C:\')
? >>> shutil.copy('C:\spam.txt', 'C:\delicious')
'C:\delicious\spam.txt'
? >>> shutil.copy('eggs.txt', 'C:\delicious\eggs2.txt')
' C:\delicious\eggs2.txt'
shutil.copytree(dir1,dir2) dir2文件夾復制dir1
shutil.move(file1,dir1) 移動
shutil.move(file1,file2) 改名
os.unlink() 刪除文件
shutil.rmtree 刪除文件夾
? 用os.unlink(path)將刪除path 處的文件。
? 調用os.rmdir(path)將刪除path 處的文件夾。該文件夾必須為空,其中沒有任
何文件和文件夾。
? 調用shutil.rmtree(path)將刪除path 處的文件夾,它包含的所有文件和文件夾都
會被刪除。
for dirname,subdirnames,filenames in os.walk(xx)
12 zipfile
>>> import zipfile, os
>>> os.chdir('C:\') # move to the folder with example.zip
>>> exampleZip = zipfile.ZipFile('example.zip')
>>> exampleZip.namelist()
['spam.txt', 'cats/', 'cats/catnames.txt', 'cats/zophie.jpg']
>>> spamInfo = exampleZip.getinfo('spam.txt')
>>> spamInfo.file_size
13908
>>> spamInfo.compress_size
3828
? >>> 'Compressed file is %sx smaller!' % (round(spamInfo.file_size / spamInfo
.compress_size, 2))
'Compressed file is 3.63x smaller!'
>>> exampleZip.close()
解壓
>>> import zipfile, os
>>> os.chdir('C:\') # move to the folder with example.zip
>>> exampleZip = zipfile.ZipFile('example.zip')
? >>> exampleZip.extractall()
>>> exampleZip.close()
單獨解壓
>>> exampleZip.extract('spam.txt')
'C:\spam.txt'
>>> exampleZip.extract('spam.txt', 'C:\some\new\folders')
'C:\some\new\folders\spam.txt'
exampleZip.close()
壓縮:
import zipfile
newZip = zipfile.ZipFile('new.zip', 'w')
newZip.write('spam.txt', compress_type=zipfile.ZIP_DEFLATED)
newZip.close()
13
traceback.format_exec()
啟動瀏覽器,打開頁面:
import webbrowser
webbrowser.open('http://inventwithpython.com/')
beautifulsoup的soup select
soup.select('div') 所有名為<div>的元素
soup.select('#author') 帶有id 屬性為author 的元素
soup.select('.notice') 所有使用CSS class 屬性名為notice 的元素
soup.select('div span') 所有在<div>元素之內的<span>元素
soup.select('div > span') 所有直接在<div>元素之內的<span>元素,中間沒有其他元素
soup.select('input[name]') 所有名為<input>,并有一個name 屬性,其值無所謂的元素
soup.select('input[type="button"]') 所有名為<input>,并有一個type 屬性,其值為button 的元素
res.raise_for_status() 不存在就異常
res = requests.get(url)
res.raise_for_status()
14 selenium 中的 WebDriver 犯法:
browser.find_element_by_class_name(name)
browser.find_elements_by_class_name(name)
使用CSS 類name 的元素
browser.find_element_by_css_selector(selector)
browser.find_elements_by_css_selector(selector)
匹配CSS selector 的元素
browser.find_element_by_id(id)
browser.find_elements_by_id(id)
匹配id 屬性值的元素
browser.find_element_by_link_text(text)
browser.find_elements_by_link_text(text)
完全匹配提供的text 的<a>元素
browser.find_element_by_partial_link_text(text)
browser.find_elements_by_partial_link_text(text)
包含提供的text 的<a>元素
browser.find_element_by_name(name)
browser.find_elements_by_name(name)
匹配name 屬性值的元素
browser.find_element_by_tag_name(name)
browser.find_elements_by_tag_name(name)
匹配標簽name 的元素
(大小寫無關,<a>元素匹配'a'和'A')
WebElement的屬性和方法:
tag_name 標簽名,例如 'a'表示<a>元素
get_attribute(name) 該元素name 屬性的值
text 該元素內的文本,例如<span>hello</span>中的'hello'
clear() 對于文本字段或文本區(qū)域元素,清除其中輸入的文本
is_displayed() 如果該元素可見,返回True,否則返回False
is_enabled() 對于輸入元素,如果該元素啟用,返回True,否則返回False
is_selected() 對于復選框或單選框元素,如果該元素被選中,選擇True,否則返回False
location 一個字典,包含鍵'x'和'y',表示該元素在頁面上的位置
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://inventwithpython.com')
try:
elem = browser.find_element_by_class_name('bookcover')
print('Found <%s> element with that class name!' % (elem.tag_name))
except:
print('Was not able to find an element with that name.')
元素點擊:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://inventwithpython.com')
linkElem = browser.find_element_by_link_text('Read It Online')
type(linkElem)
<class 'selenium.webdriver.remote.webelement.WebElement'>
linkElem.click() # follows the "Read It Online" link
輸入內容:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://gmail.com')
emailElem = browser.find_element_by_id('Email')
emailElem.send_keys('not_my_real_email@gmail.com')
passwordElem = browser.find_element_by_id('Passwd')
passwordElem.send_keys('12345')
passwordElem.submit()
selenium.webdriver.common.keys 中常用變量
Keys.DOWN, Keys.UP, Keys.LEFT,Keys.RIGHT 鍵盤箭頭鍵
Keys.ENTER, Keys.RETURN 回車和換行鍵
Keys.HOME, Keys.END,
Keys.PAGE_DOWN,Keys.PAGE_UP
Home 鍵、End 鍵、PageUp 鍵和Page Down 鍵
Keys.ESCAPE, Keys.BACK_SPACE,Keys.DELETE Esc、Backspace 和字母鍵
Keys.F1, Keys.F2, . . . , Keys.F12 鍵盤頂部的F1 到F12 鍵
Keys.TAB Tab 鍵
模擬按鍵
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Firefox()
browser.get('http://nostarch.com')
htmlElem = browser.find_element_by_tag_name('html')
htmlElem.send_keys(Keys.END) # scrolls to bottom
htmlElem.send_keys(Keys.HOME) # scrolls to top
瀏覽器按鈕:
browser.back()點擊“返回”按鈕。
browser.forward()點擊“前進”按鈕。
browser.refresh()點擊“刷新”按鈕。
browser.quit()點擊“關閉窗口”按鈕。
15 openpyxl
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
type(wb)
<class 'openpyxl.workbook.workbook.Workbook'>
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
wb.get_sheet_names()
['Sheet1', 'Sheet2', 'Sheet3']
sheet = wb.get_sheet_by_name('Sheet3')
sheet
browser.get('http://gmail.com')
>>> emailElem = browser.find_element_by_id('Email')
>>> emailElem.send_keys('not_my_real_email@gmail.com')
>>> passwordElem = browser.find_element_by_id('Passwd')
>>> passwordElem.send_keys('12345')
>>> passwordElem.submit()
selenium.webdriver.common.keys 中常用變量
Keys.DOWN, Keys.UP, Keys.LEFT,Keys.RIGHT 鍵盤箭頭鍵
Keys.ENTER, Keys.RETURN 回車和換行鍵
Keys.HOME, Keys.END,
Keys.PAGE_DOWN,Keys.PAGE_UP
Home 鍵、End 鍵、PageUp 鍵和Page Down 鍵
Keys.ESCAPE, Keys.BACK_SPACE,Keys.DELETE Esc、Backspace 和字母鍵
Keys.F1, Keys.F2, . . . , Keys.F12 鍵盤頂部的F1 到F12 鍵
Keys.TAB Tab 鍵
模擬按鍵
>>> from selenium import webdriver
>>> from selenium.webdriver.common.keys import Keys
>>> browser = webdriver.Firefox()
>>> browser.get('http://nostarch.com')
>>> htmlElem = browser.find_element_by_tag_name('html')
>>> htmlElem.send_keys(Keys.END) # scrolls to bottom
>>> htmlElem.send_keys(Keys.HOME) # scrolls to top
瀏覽器按鈕:
browser.back()點擊“返回”按鈕。
browser.forward()點擊“前進”按鈕。
browser.refresh()點擊“刷新”按鈕。
browser.quit()點擊“關閉窗口”按鈕。
15 openpyxl
>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> type(wb)
<class 'openpyxl.workbook.workbook.Workbook'>
>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> wb.get_sheet_names()
['Sheet1', 'Sheet2', 'Sheet3']
>>> sheet = wb.get_sheet_by_name('Sheet3')
>>> sheet
<Worksheet "Sheet3">
type(sheet)
<class 'openpyxl.worksheet.worksheet.Worksheet'>
sheet.title
'Sheet3'
anotherSheet = wb.get_active_sheet()
anotherSheet
<Worksheet "Sheet1">
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
sheet['A1']
<Cell Sheet1.A1>
sheet['A1'].value
datetime.datetime(2015, 4, 5, 13, 34, 2)
c = sheet['B1']
c.value
'Apples'
'Row ' + str(c.row) + ', Column ' + c.column + ' is ' + c.value
'Row 1, Column B is Apples'
'Cell ' + c.coordinate + ' is ' + c.value
'Cell B1 is Apples'
sheet['C1'].valuefrom selenium.webdriver.common.keys import Keys
>>> browser = webdriver.Firefox()
>>> browser.get('http://nostarch.com')
>>> htmlElem = browser.find_element_by_tag_name('html')
>>> htmlElem.send_keys(Keys.END) # scrolls to bottom
>>> htmlElem.send_keys(Keys.HOME) # scrolls to top
瀏覽器按鈕:
browser.back()點擊“返回”按鈕。
browser.forward()點擊“前進”按鈕。
browser.refresh()點擊“刷新”按鈕。
browser.quit()點擊“關閉窗口”按鈕。
15 openpyxl
>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> type(wb)
<class 'openpyxl.workbook.workbook.Workbook'>
>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> wb.get_sheet_names()
['Sheet1', 'Sheet2', 'Sheet3']
>>> sheet = wb.get_sheet_by_name('Sheet3')
>>> sheet
<Worksheet "Sheet3">
>>> type(sheet)
<class 'openpyxl.worksheet.worksheet.Worksheet'>
>>> sheet.title
'Sheet3'
>>> anotherSheet = wb.get_active_sheet()
>>> anotherSheet
<Worksheet "Sheet1">
>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> sheet = wb.get_sheet_by_name('Sheet1')
>>> sheet['A1']
<Cell Sheet1.A1>
>>> sheet['A1'].value
datetime.datetime(2015, 4, 5, 13, 34, 2)
>>> c = sheet['B1']
>>> c.value
'Apples'
>>> 'Row ' + str(c.row) + ', Column ' + c.column + ' is ' + c.value
'Row 1, Column B is Apples'
>>> 'Cell ' + c.coordinate + ' is ' + c.value
'Cell B1 is Apples'
>>> sheet['C1'].value
73
sheet.cell(row=1, column=2)
<Cell Sheet1.B1>
sheet.cell(row=1, column=2).value
'Apples'
for i in range(1, 8, 2):
print(i, sheet.cell(row=i, column=2).value)
1 Apples
htmlElem.send_keys(Keys.END) # scrolls to bottom
>>> htmlElem.send_keys(Keys.HOME) # scrolls to top
瀏覽器按鈕:
browser.back()點擊“返回”按鈕。
browser.forward()點擊“前進”按鈕。
browser.refresh()點擊“刷新”按鈕。
browser.quit()點擊“關閉窗口”按鈕。
15 openpyxl
>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> type(wb)
<class 'openpyxl.workbook.workbook.Workbook'>
>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> wb.get_sheet_names()
['Sheet1', 'Sheet2', 'Sheet3']
>>> sheet = wb.get_sheet_by_name('Sheet3')
>>> sheet
<Worksheet "Sheet3">
>>> type(sheet)
<class 'openpyxl.worksheet.worksheet.Worksheet'>
>>> sheet.title
'Sheet3'
>>> anotherSheet = wb.get_active_sheet()
>>> anotherSheet
<Worksheet "Sheet1">
>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> sheet = wb.get_sheet_by_name('Sheet1')
>>> sheet['A1']
<Cell Sheet1.A1>
>>> sheet['A1'].value
datetime.datetime(2015, 4, 5, 13, 34, 2)
>>> c = sheet['B1']
>>> c.value
'Apples'
>>> 'Row ' + str(c.row) + ', Column ' + c.column + ' is ' + c.value
'Row 1, Column B is Apples'
>>> 'Cell ' + c.coordinate + ' is ' + c.value
'Cell B1 is Apples'
>>> sheet['C1'].value
73
>>> sheet.cell(row=1, column=2)
<Cell Sheet1.B1>
>>> sheet.cell(row=1, column=2).value
'Apples'
>>> for i in range(1, 8, 2):
print(i, sheet.cell(row=i, column=2).value)
1 Apples
3 Pears
5 Apples
7 Strawberries
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
sheet.get_highest_row()
7
sheet.get_highest_column()
3
import openpyxl
from openpyxl.cell import get_column_letter, column_index_from_string
get_column_letter(1)
'A'
get_column_letter(2)
import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> wb.get_sheet_names()
['Sheet1', 'Sheet2', 'Sheet3']
>>> sheet = wb.get_sheet_by_name('Sheet3')
>>> sheet
<Worksheet "Sheet3">
>>> type(sheet)
<class 'openpyxl.worksheet.worksheet.Worksheet'>
>>> sheet.title
'Sheet3'
>>> anotherSheet = wb.get_active_sheet()
>>> anotherSheet
<Worksheet "Sheet1">
>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> sheet = wb.get_sheet_by_name('Sheet1')
>>> sheet['A1']
<Cell Sheet1.A1>
>>> sheet['A1'].value
datetime.datetime(2015, 4, 5, 13, 34, 2)
>>> c = sheet['B1']
>>> c.value
'Apples'
>>> 'Row ' + str(c.row) + ', Column ' + c.column + ' is ' + c.value
'Row 1, Column B is Apples'
>>> 'Cell ' + c.coordinate + ' is ' + c.value
'Cell B1 is Apples'
>>> sheet['C1'].value
73
>>> sheet.cell(row=1, column=2)
<Cell Sheet1.B1>
>>> sheet.cell(row=1, column=2).value
'Apples'
>>> for i in range(1, 8, 2):
print(i, sheet.cell(row=i, column=2).value)
1 Apples
3 Pears
5 Apples
7 Strawberries
>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> sheet = wb.get_sheet_by_name('Sheet1')
>>> sheet.get_highest_row()
7
>>> sheet.get_highest_column()
3
>>> import openpyxl
>>> from openpyxl.cell import get_column_letter, column_index_from_string
>>> get_column_letter(1)
'A'
>>> get_column_letter(2)
'B'
get_column_letter(27)
'AA'
get_column_letter(900)
'AHP'
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
get_column_letter(sheet.get_highest_column())
'C'
column_index_from_string('A')
1
column_index_from_string('AA')
27
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
tuple(sheet['A1':'C3'])
((<Cell Sheet1.A1>, <Cell Sheet1.B1>, <Cell Sheet1.C1>), (<Cell Sheet1.A2>,
<Cell Sheet1.B2>, <Cell Sheet1.C2>), (<Cell Sheet1.A3>, <Cell Sheet1.B3>,
<Cell Sheet1.C3>))
c.value
'Apples'
>>> 'Row ' + str(c.row) + ', Column ' + c.column + ' is ' + c.value
'Row 1, Column B is Apples'
>>> 'Cell ' + c.coordinate + ' is ' + c.value
'Cell B1 is Apples'
>>> sheet['C1'].value
73
>>> sheet.cell(row=1, column=2)
<Cell Sheet1.B1>
>>> sheet.cell(row=1, column=2).value
'Apples'
>>> for i in range(1, 8, 2):
print(i, sheet.cell(row=i, column=2).value)
1 Apples
3 Pears
5 Apples
7 Strawberries
>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> sheet = wb.get_sheet_by_name('Sheet1')
>>> sheet.get_highest_row()
7
>>> sheet.get_highest_column()
3
>>> import openpyxl
>>> from openpyxl.cell import get_column_letter, column_index_from_string
>>> get_column_letter(1)
'A'
>>> get_column_letter(2)
'B'
>>> get_column_letter(27)
'AA'
>>> get_column_letter(900)
'AHP'
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> sheet = wb.get_sheet_by_name('Sheet1')
>>> get_column_letter(sheet.get_highest_column())
'C'
>>> column_index_from_string('A')
1
>>> column_index_from_string('AA')
27
>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> sheet = wb.get_sheet_by_name('Sheet1')
>>> tuple(sheet['A1':'C3'])
((<Cell Sheet1.A1>, <Cell Sheet1.B1>, <Cell Sheet1.C1>), (<Cell Sheet1.A2>,
<Cell Sheet1.B2>, <Cell Sheet1.C2>), (<Cell Sheet1.A3>, <Cell Sheet1.B3>,
<Cell Sheet1.C3>))
? >>> for rowOfCellObjects in sheet['A1':'C3']:
? for cellObj in rowOfCellObjects:
print(cellObj.coordinate, cellObj.value)
print('--- END OF ROW ---')
A1 2015-04-05 13:34:02
B1 Apples
C1 73
--- END OF ROW ---
A2 2015-04-05 03:41:23
B2 Cherries
C2 85
--- END OF ROW ---
A3 2015-04-06 12:46:51
B3 Pears
C3 14
--- END OF ROW ---
import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_active_sheet()
sheet.columns[1]
(<Cell Sheet1.B1>, <Cell Sheet1.B2>, <Cell Sheet1.B3>, <Cell Sheet1.B4>,
<Cell Sheet1.B5>, <Cell Sheet1.B6>, <Cell Sheet1.B7>)
for cellObj in sheet.columns[1]:
from openpyxl.cell import get_column_letter, column_index_from_string
>>> get_column_letter(1)
'A'
>>> get_column_letter(2)
'B'
>>> get_column_letter(27)
'AA'
>>> get_column_letter(900)
'AHP'
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> sheet = wb.get_sheet_by_name('Sheet1')
>>> get_column_letter(sheet.get_highest_column())
'C'
>>> column_index_from_string('A')
1
>>> column_index_from_string('AA')
27
>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> sheet = wb.get_sheet_by_name('Sheet1')
>>> tuple(sheet['A1':'C3'])
((<Cell Sheet1.A1>, <Cell Sheet1.B1>, <Cell Sheet1.C1>), (<Cell Sheet1.A2>,
<Cell Sheet1.B2>, <Cell Sheet1.C2>), (<Cell Sheet1.A3>, <Cell Sheet1.B3>,
<Cell Sheet1.C3>))
? >>> for rowOfCellObjects in sheet['A1':'C3']:
? for cellObj in rowOfCellObjects:
print(cellObj.coordinate, cellObj.value)
print('--- END OF ROW ---')
A1 2015-04-05 13:34:02
B1 Apples
C1 73
--- END OF ROW ---
A2 2015-04-05 03:41:23
B2 Cherries
C2 85
--- END OF ROW ---
A3 2015-04-06 12:46:51
B3 Pears
C3 14
--- END OF ROW ---
>>> import openpyxl
>>> wb = openpyxl.load_workbook('example.xlsx')
>>> sheet = wb.get_active_sheet()
>>> sheet.columns[1]
(<Cell Sheet1.B1>, <Cell Sheet1.B2>, <Cell Sheet1.B3>, <Cell Sheet1.B4>,
<Cell Sheet1.B5>, <Cell Sheet1.B6>, <Cell Sheet1.B7>)
>>> for cellObj in sheet.columns[1]:
print(cellObj.value)
16\
import time
time.time()
1425063955.068649
time.sleep(1)
datetime.datetime.now()
import datetime
? >>> datetime.datetime.now()
? datetime.datetime(2015, 2, 27, 11, 10, 49, 55, 53)
? >>> dt = datetime.datetime(2015, 10, 21, 16, 29, 0)
? >>> dt.year, dt.month, dt.day
(2015, 10, 21)
? >>> dt.hour, dt.minute, dt.second
(16, 29, 0)
datetime.datetime.fromtimestamp(100000000000)
datetime.timedelta 一段時間
delta = datetime.timedelta(days=11, hours=10, minutes=9, seconds=8)
? >>> delta.days, delta.seconds, delta.microseconds
(11, 36548, 0)
delta.total_seconds()
986948.0
str(delta)
'11 days, 10:09:08'
暫停直到指定日期:
import datetime
import time
halloween2016 = datetime.datetime(2016, 10, 31, 0, 0, 0)
while datetime.datetime.now() < halloween2016:
time.sleep(1)
日期格式化:strftime
oct21st = datetime.datetime(2015, 10, 21, 16, 29, 0)
oct21st.strftime('%Y/%m/%d %H:%M:%S')
'2015/10/21 16:29:00'
oct21st.strftime('%I:%M %p')
'04:29 PM'
oct21st.strftime("%B of '%y")
"October of '15"
字符串轉成日期:strptime
datetime.datetime.strptime('October 21, 2015', '%B %d, %Y')
sheet = wb.get_active_sheet()
>>> sheet.columns[1]
(<Cell Sheet1.B1>, <Cell Sheet1.B2>, <Cell Sheet1.B3>, <Cell Sheet1.B4>,
<Cell Sheet1.B5>, <Cell Sheet1.B6>, <Cell Sheet1.B7>)
>>> for cellObj in sheet.columns[1]:
print(cellObj.value)
16\
>>> import time
>>> time.time()
1425063955.068649
time.sleep(1)
datetime.datetime.now()
>>> import datetime
? >>> datetime.datetime.now()
? datetime.datetime(2015, 2, 27, 11, 10, 49, 55, 53)
? >>> dt = datetime.datetime(2015, 10, 21, 16, 29, 0)
? >>> dt.year, dt.month, dt.day
(2015, 10, 21)
? >>> dt.hour, dt.minute, dt.second
(16, 29, 0)
datetime.datetime.fromtimestamp(100000000000)
datetime.timedelta 一段時間
>>> delta = datetime.timedelta(days=11, hours=10, minutes=9, seconds=8)
? >>> delta.days, delta.seconds, delta.microseconds
(11, 36548, 0)
>>> delta.total_seconds()
986948.0
>>> str(delta)
'11 days, 10:09:08'
暫停直到指定日期:
import datetime
import time
halloween2016 = datetime.datetime(2016, 10, 31, 0, 0, 0)
while datetime.datetime.now() < halloween2016:
time.sleep(1)
日期格式化:strftime
>>> oct21st = datetime.datetime(2015, 10, 21, 16, 29, 0)
>>> oct21st.strftime('%Y/%m/%d %H:%M:%S')
'2015/10/21 16:29:00'
>>> oct21st.strftime('%I:%M %p')
'04:29 PM'
>>> oct21st.strftime("%B of '%y")
"October of '15"
字符串轉成日期:strptime
>>> datetime.datetime.strptime('October 21, 2015', '%B %d, %Y')
datetime.datetime(2015, 10, 21, 0, 0)
datetime.datetime.strptime('2015/10/21 16:29:00', '%Y/%m/%d %H:%M:%S')
datetime.datetime(2015, 10, 21, 16, 29)
datetime.datetime.strptime("October of '15", "%B of '%y")
datetime.datetime(2015, 10, 1, 0, 0)
datetime.datetime.strptime("November of '63", "%B of '%y")
datetime.datetime(2063, 11, 1, 0, 0)
17 線程!
import threading, time
print('Start of program.')
? def takeANap():
time.sleep(5)
print('Wake up!')
? threadObj = threading.Thread(target=takeANap)
? threadObj.start()
print('End of program.')
threading.Thread(target=xx)
x.start()
threading.Thread(target=x,args=[1,3,4],kwargs={x:x,y:y})
18 subprocess.Ppopen()
import subprocess
subprocess.Popen('C:\Windows\System32\calc.exe')
返回值是一個Popen 對象,它有兩個有用的方法:poll()和wait()。
可以認為poll()方法是問你的朋友,她是否執(zhí)行完畢你給她的代碼。如果這個
進程在poll()調用時仍在運行,poll()方法就返回None。如果該程序已經(jīng)終止,
它會返回該進程的整數(shù)退出代碼。退出代碼用于說明進程是無錯終止(退出代碼
為0),還是一個錯誤導致進程終止(退出代碼非零,通常為1,但可能根據(jù)程序
而不同)。
wait()方法就像是等著你的朋友執(zhí)行完她的代碼,然后你繼續(xù)執(zhí)行你的代碼。
wait()方法將阻塞,直到啟動的進程終止。如果你希望你的程序暫停,直到用戶完成
與其他程序,這非常有用。wait()的返回值是進程的整數(shù)退出代碼。
xx.poll()
xx.wait() 阻塞
傳遞參數(shù):
subprocess.Popen(['C:\Windows\notepad.exe', 'C:\hello.txt'])
用系統(tǒng)默認程序播放聲音,linux上start要改成open
subprocess.Popen(['start', 'alarm.wav'], shell=True)
21 發(fā)短信:twilio
from twilio.rest import TwilioRestClient
accountSID = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
authToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
? >>> twilioCli = TwilioRestClient(accountSID, authToken)
myTwilioNumber = '+14955551234'
myCellPhone = '+14955558888'
? >>> message = twilioCli.messages.create(body='Mr. Watson - Come here - I want
to see you.', from_=myTwilioNumber, to=myCellPhone)
22 Pillow獲取顏色
from PIL import ImageColor
? >>> ImageColor.getcolor('red', 'RGBA')
(255, 0, 0, 255)
? >>> ImageColor.getcolor('RED', 'RGBA')
(255, 0, 0, 255)
ImageColor.getcolor('Black', 'RGBA')
(0, 0, 0, 255)
ImageColor.getcolor('chocolate', 'RGBA')
(210, 105, 30, 255)
ImageColor.getcolor('CornflowerBlue', 'RGBA')
(100, 149, 237, 255)
打開圖像
Image.open(xx.png)
from PIL import Image
catIm = Image.open('zophie.png')
獲取圖像像素
from PIL import Image
catIm = Image.open('zophie.png')
catIm.size
filename,format
format_description
save
畫純顏色圖片
from PIL import Image
? >>> im = Image.new('RGBA', (100, 200), 'purple')
im.save('purpleImage.png')
? >>> im2 = Image.new('RGBA', (20, 20))
im2.save('transparentImage.png')
剪裁圖片
croppedIm = catIm.crop((335, 345, 565, 560))
croppedIm.save('cropped.png')
復制和粘貼圖片
catIm = Image.open('zophie.png')
catCopyIm = catIm.copy()
faceIm = catIm.crop((335, 345, 565, 560))
faceIm.size
(230, 215)
catCopyIm.paste(faceIm, (0, 0))
catCopyIm.paste(faceIm, (400, 500))
catCopyIm.save('pasted.png')
平鋪圖像
catImWidth, catImHeight = catIm.size
faceImWidth, faceImHeight = faceIm.size
? >>> catCopyTwo = catIm.copy()
? >>> for left in range(0, catImWidth, faceImWidth):
? for top in range(0, catImHeight, faceImHeight):
print(left, top)
catCopyTwo.paste(faceIm, (left, top))
調整圖像大小
width, height = catIm.size
? >>> quartersizedIm = catIm.resize((int(width / 2), int(height / 2)))
quartersizedIm.save('quartersized.png')
? >>> svelteIm = catIm.resize((width, height + 300))
svelteIm.save('svelte.png')ImageColor.getcolor('CornflowerBlue', 'RGBA')
(100, 149, 237, 255)
打開圖像
Image.open(xx.png)
>>> from PIL import Image
>>> catIm = Image.open('zophie.png')
獲取圖像像素
>>> from PIL import Image
>>> catIm = Image.open('zophie.png')
>>> catIm.size
filename,format
format_description
save
畫純顏色圖片
>>> from PIL import Image
? >>> im = Image.new('RGBA', (100, 200), 'purple')
>>> im.save('purpleImage.png')
? >>> im2 = Image.new('RGBA', (20, 20))
>>> im2.save('transparentImage.png')
剪裁圖片
>>> croppedIm = catIm.crop((335, 345, 565, 560))
>>> croppedIm.save('cropped.png')
復制和粘貼圖片
>>> catIm = Image.open('zophie.png')
>>> catCopyIm = catIm.copy()
>>> faceIm = catIm.crop((335, 345, 565, 560))
>>> faceIm.size
(230, 215)
>>> catCopyIm.paste(faceIm, (0, 0))
>>> catCopyIm.paste(faceIm, (400, 500))
>>> catCopyIm.save('pasted.png')
平鋪圖像
>>> catImWidth, catImHeight = catIm.size
>>> faceImWidth, faceImHeight = faceIm.size
? >>> catCopyTwo = catIm.copy()
? >>> for left in range(0, catImWidth, faceImWidth):
? for top in range(0, catImHeight, faceImHeight):
print(left, top)
catCopyTwo.paste(faceIm, (left, top))
調整圖像大小
>>> width, height = catIm.size
? >>> quartersizedIm = catIm.resize((int(width / 2), int(height / 2)))
>>> quartersizedIm.save('quartersized.png')
? >>> svelteIm = catIm.resize((width, height + 300))
>>> svelteIm.save('svelte.png')
翻轉圖像
catIm.rotate(90).save('rotated90.png')
catIm.rotate(180).save('rotated180.png')catIm.rotate(270).save('rotated270.png')
翻轉并擴大
catIm.rotate(6).save('rotated6.png')
catIm.rotate(6, expand=True).save('rotated6_expanded.png')
翻轉(整面)
catIm.transpose(Image.FLIP_LEFT_RIGHT).save('horizontal_flip.png')
catIm.transpose(Image.FLIP_TOP_BOTTOM).save('vertical_flip.png')
image.png
更改像素
im = Image.new('RGBA', (100, 100))
? >>> im.getpixel((0, 0))
(0, 0, 0, 0)
? >>> for x in range(100):
for y in range(50):
? im.putpixel((x, y), (210, 210, 210))
from PIL import ImageColor
? >>> for x in range(100):
for y in range(50, 100):
catCopyIm.save('pasted.png')
平鋪圖像
>>> catImWidth, catImHeight = catIm.size
>>> faceImWidth, faceImHeight = faceIm.size
? >>> catCopyTwo = catIm.copy()
? >>> for left in range(0, catImWidth, faceImWidth):
? for top in range(0, catImHeight, faceImHeight):
print(left, top)
catCopyTwo.paste(faceIm, (left, top))
調整圖像大小
>>> width, height = catIm.size
? >>> quartersizedIm = catIm.resize((int(width / 2), int(height / 2)))
>>> quartersizedIm.save('quartersized.png')
? >>> svelteIm = catIm.resize((width, height + 300))
>>> svelteIm.save('svelte.png')
翻轉圖像
>>> catIm.rotate(90).save('rotated90.png')
>>> catIm.rotate(180).save('rotated180.png')
>>> catIm.rotate(270).save('rotated270.png')
翻轉并擴大
>>> catIm.rotate(6).save('rotated6.png')
>>> catIm.rotate(6, expand=True).save('rotated6_expanded.png')
翻轉(整面)
>>> catIm.transpose(Image.FLIP_LEFT_RIGHT).save('horizontal_flip.png')
>>> catIm.transpose(Image.FLIP_TOP_BOTTOM).save('vertical_flip.png')
image.png
更改像素
>>> im = Image.new('RGBA', (100, 100))
? >>> im.getpixel((0, 0))
(0, 0, 0, 0)
? >>> for x in range(100):
for y in range(50):
? im.putpixel((x, y), (210, 210, 210))
>>> from PIL import ImageColor
? >>> for x in range(100):
for y in range(50, 100):
? im.putpixel((x, y), ImageColor.getcolor('darkgray', 'RGBA'))
im.getpixel((0, 0))
(210, 210, 210, 255)
im.getpixel((0, 50))
(169, 169, 169, 255)
im.save('putPixel.png')
畫圖:
from PIL import Image, ImageDraw
im = Image.new('RGBA', (200, 200), 'white')
draw = ImageDraw.Draw(im)
點
point(xy, fill)方法繪制單個像素。xy 參數(shù)表示要畫的點的列表。該列表可以是x
quartersizedIm = catIm.resize((int(width / 2), int(height / 2)))
>>> quartersizedIm.save('quartersized.png')
? >>> svelteIm = catIm.resize((width, height + 300))
>>> svelteIm.save('svelte.png')
翻轉圖像
>>> catIm.rotate(90).save('rotated90.png')
>>> catIm.rotate(180).save('rotated180.png')
>>> catIm.rotate(270).save('rotated270.png')
翻轉并擴大
>>> catIm.rotate(6).save('rotated6.png')
>>> catIm.rotate(6, expand=True).save('rotated6_expanded.png')
翻轉(整面)
>>> catIm.transpose(Image.FLIP_LEFT_RIGHT).save('horizontal_flip.png')
>>> catIm.transpose(Image.FLIP_TOP_BOTTOM).save('vertical_flip.png')
image.png
更改像素
>>> im = Image.new('RGBA', (100, 100))
? >>> im.getpixel((0, 0))
(0, 0, 0, 0)
? >>> for x in range(100):
for y in range(50):
? im.putpixel((x, y), (210, 210, 210))
>>> from PIL import ImageColor
? >>> for x in range(100):
for y in range(50, 100):
? im.putpixel((x, y), ImageColor.getcolor('darkgray', 'RGBA'))
>>> im.getpixel((0, 0))
(210, 210, 210, 255)
>>> im.getpixel((0, 50))
(169, 169, 169, 255)
> >> im.save('putPixel.png')
畫圖:
>>> from PIL import Image, ImageDraw
>>> im = Image.new('RGBA', (200, 200), 'white')
>>> draw = ImageDraw.Draw(im)
點
point(xy, fill)方法繪制單個像素。xy 參數(shù)表示要畫的點的列表。該列表可以是x
和y 坐標的元組的列表,例如[(x, y), (x, y), ...],或是沒有元組的x 和y 坐標的列表,
例如[x1, y1, x2, y2, ...]。fill 參數(shù)是點的顏色,要么是一個RGBA 元組,要么是顏色
名稱的字符串,如'red'。fill 參數(shù)是可選的。
線
line(xy, fill, width)方法繪制一條線或一系列的線。xy 要么是一個元組的列表,
例如[(x, y), (x, y), ...],要么是一個整數(shù)列表,例如[x1, y1, x2, y2, ...]。每個點都是正
在繪制的線上的一個連接點??蛇x的fill 參數(shù)是線的顏色,是一個RGBA 元組或顏色
名稱。可選的width 參數(shù)是線的寬度,如果未指定,缺省值為1。
矩形
rectangle(xy, fill, outline)方法繪制一個矩形。xy 參數(shù)是一個矩形元組,形式為(left,
top, right, bottom)。left 和top 值指定了矩形左上角的x 和y 坐標,right 和bottom 指定
了矩形的右下角??蛇x的fill 參數(shù)是顏色,將填充該矩形的內部。可選的outline 參
數(shù)是矩形輪廓的顏色。
橢圓
ellipse(xy, fill, outline)方法繪制一個橢圓。如果橢圓的寬度和高度一樣,該方法將繪
制一個圓。xy 參數(shù)是一個矩形元組(left, top, right, bottom),它表示正好包含該橢圓的
矩形??蛇x的fill 參數(shù)是橢圓內的顏色,可選的outline 參數(shù)是橢圓輪廓的顏色。
多邊形
polygon(xy, fill, outline)方法繪制任意的多邊形。xy 參數(shù)是一個元組列表,例如
[(x, y), (x, y), ...],或者是一個整數(shù)列表,例如[x1, y1, x2, y2, ...],表示多邊形邊的連
接點。最后一對坐標將自動連接到第一對坐標??蛇x的fill 參數(shù)是多邊形內部的顏
色,可選的outline 參數(shù)是多邊形輪廓的顏色。
from PIL import Image, ImageDraw
im = Image.new('RGBA', (200, 200), 'white')
draw = ImageDraw.Draw(im)
? >>> draw.line([(0, 0), (199, 0), (199, 199), (0, 199), (0, 0)], fill='black')
? >>> draw.rectangle((20, 30, 60, 60), fill='blue')
? >>> draw.ellipse((120, 30, 160, 60), fill='red')
? >>> draw.polygon(((57, 87), (79, 62), (94, 85), (120, 90), (103, 113)),
fill='brown')
? >>> for i in range(100, 200, 10):
draw.line([(i, 0), (200, i - 100)], fill='green')
im.save('drawing.png')
寫字
from PIL import Image, ImageDraw, ImageFont
import os
? >>> im = Image.new('RGBA', (200, 200), 'white')
draw = ImageDraw.Draw(im)
? >>> draw.text((20, 150), 'Hello', fill='purple')
fontsFolder = 'FONT_FOLDER' # e.g. ‘/Library/Fonts’
? >>> arialFont = ImageFont.truetype(os.path.join(fontsFolder, 'arial.ttf'), 32)
? >>> draw.text((100, 150), 'Howdy', fill='gray', font=arialFont)
im.save('text.png')
