前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python编程快速上手

python编程快速上手

作者头像
用户5760343
发布2022-05-13 18:31:04
2260
发布2022-05-13 18:31:04
举报
文章被收录于专栏:sktj

1、 5//2=2 5/2=2.5 2、全局变量 global foo 3、list.index(xx) 没有则引发异常 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.'

不区分大小写: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.' 不区分大小写: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() 对于文本字段或文本区域元素,清除其中输入的文本 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'].value 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'].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()方法是问你的朋友,她是否执行完毕你给她的代码。如果这个 进程在poll()调用时仍在运行,poll()方法就返回None。如果该程序已经终止, 它会返回该进程的整数退出代码。退出代码用于说明进程是无错终止(退出代码 为0),还是一个错误导致进程终止(退出代码非零,通常为1,但可能根据程序 而不同)。 wait()方法就像是等着你的朋友执行完她的代码,然后你继续执行你的代码。 wait()方法将阻塞,直到启动的进程终止。如果你希望你的程序暂停,直到用户完成 与其他程序,这非常有用。wait()的返回值是进程的整数退出代码。 xx.poll() xx.wait() 阻塞 传递参数: subprocess.Popen(['C:\Windows\notepad.exe', 'C:\hello.txt']) 用系统默认程序播放声音,linux上start要改成open subprocess.Popen(['start', 'alarm.wav'], shell=True)

21 发短信: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 参数表示要画的点的列表。该列表可以是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 参数表示要画的点的列表。该列表可以是x 和y 坐标的元组的列表,例如[(x, y), (x, y), ...],或是没有元组的x 和y 坐标的列表, 例如[x1, y1, x2, y2, ...]。fill 参数是点的颜色,要么是一个RGBA 元组,要么是颜色 名称的字符串,如'red'。fill 参数是可选的。 线 line(xy, fill, width)方法绘制一条线或一系列的线。xy 要么是一个元组的列表, 例如[(x, y), (x, y), ...],要么是一个整数列表,例如[x1, y1, x2, y2, ...]。每个点都是正 在绘制的线上的一个连接点。可选的fill 参数是线的颜色,是一个RGBA 元组或颜色 名称。可选的width 参数是线的宽度,如果未指定,缺省值为1。 矩形 rectangle(xy, fill, outline)方法绘制一个矩形。xy 参数是一个矩形元组,形式为(left, top, right, bottom)。left 和top 值指定了矩形左上角的x 和y 坐标,right 和bottom 指定 了矩形的右下角。可选的fill 参数是颜色,将填充该矩形的内部。可选的outline 参 数是矩形轮廓的颜色。 椭圆 ellipse(xy, fill, outline)方法绘制一个椭圆。如果椭圆的宽度和高度一样,该方法将绘 制一个圆。xy 参数是一个矩形元组(left, top, right, bottom),它表示正好包含该椭圆的 矩形。可选的fill 参数是椭圆内的颜色,可选的outline 参数是椭圆轮廓的颜色。 多边形 polygon(xy, fill, outline)方法绘制任意的多边形。xy 参数是一个元组列表,例如 [(x, y), (x, y), ...],或者是一个整数列表,例如[x1, y1, x2, y2, ...],表示多边形边的连 接点。最后一对坐标将自动连接到第一对坐标。可选的fill 参数是多边形内部的颜 色,可选的outline 参数是多边形轮廓的颜色。 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')

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
短信
腾讯云短信(Short Message Service,SMS)可为广大企业级用户提供稳定可靠,安全合规的短信触达服务。用户可快速接入,调用 API / SDK 或者通过控制台即可发送,支持发送验证码、通知类短信和营销短信。国内验证短信秒级触达,99%到达率;国际/港澳台短信覆盖全球200+国家/地区,全球多服务站点,稳定可靠。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档