Python辦公自動(dòng)化處理的10大場(chǎng)景應(yīng)用示例
引言
知乎上有個(gè)熱門問題,Python 未來會(huì)成為大眾辦公常用編程工具嗎?
在編程世界里,Python已經(jīng)是名副其實(shí)的網(wǎng)紅了。曾經(jīng)一個(gè)學(xué)漢語(yǔ)言的研究生,問我怎么學(xué)Python,因?yàn)樗麄冋n程論文里需要用到文本分析,用Python來跑數(shù)據(jù)。我和他說,你看兩天語(yǔ)法,就可以上手開干,不會(huì)的再查資料。后來這位同學(xué)半個(gè)月就用Python把論文數(shù)據(jù)搞好了。
所以Python最大優(yōu)勢(shì)在于容易學(xué),門檻比Java、C++低非常多,給非程序員群體提供了用代碼干活的可能性。當(dāng)然Python能成為大眾編程工具,不光光是因?yàn)橐讓W(xué),還因?yàn)镻ython有成千上萬的工具包,遍布各行各業(yè)。
舉10幾個(gè)辦公自動(dòng)化常見的例子,Python都能高效處理。
1、Python處理Excel數(shù)據(jù)
可以使用pandas、xlwings、openpyxl等包來對(duì)Excel進(jìn)行增刪改查、格式調(diào)整等操作,甚至可以使用Python函數(shù)來對(duì)excel數(shù)據(jù)進(jìn)行分析。
讀取excel表格
import xlwings as xw wb = xw.Book() # this will create a new workbook wb = xw.Book('FileName.xlsx') # connect to a file that is open or in the current working directory wb = xw.Book(r'C:\path\to\file.xlsx') # on Windows: use raw strings to escape backslashes
將matplotlib繪圖寫入excel表格
import matplotlib.pyplot as plt import xlwings as xw fig = plt.figure() plt.plot([1, 2, 3]) sheet = xw.Book().sheets[0] sheet.pictures.add(fig, name='MyPlot', update=True)
2、Python處理PDF文本
PDF幾乎是最常見的文本格式,很多人有各種處理PDF的需求,比如制作PDF、獲取文本、獲取圖片、獲取表格等。Python中有PyPDF、pdfplumber、ReportLab、PyMuPDF等包可以輕松實(shí)現(xiàn)這些需求。
提取PDF文字
import PyPDF2 pdfFile = open('example.pdf','rb') pdfReader = PyPDF2.PdfFileReader(pdfFile) print(pdfReader.numPages) page = pdfReader.getPage(0) print(page.extractText()) pdfFile.close()
提取PDF表格
# 提取pdf表格 import pdfplumber with pdfplumber.open("example.pdf") as pdf: page01 = pdf.pages[0] #指定頁(yè)碼 table1 = page01.extract_table()#提取單個(gè)表格 # table2 = page01.extract_tables()#提取多個(gè)表格 print(table1)
3、Python處理Email
在Python中可以使用smtplib配合email庫(kù),來實(shí)現(xiàn)郵件的自動(dòng)化傳輸,非常方便。
import smtplib import email # 負(fù)責(zé)將多個(gè)對(duì)象集合起來 from email.mime.multipart import MIMEMultipart from email.header import Header # SMTP服務(wù)器,這里使用163郵箱 mail_host = "smtp.163.com" # 發(fā)件人郵箱 mail_sender = "******@163.com" # 郵箱授權(quán)碼,注意這里不是郵箱密碼,如何獲取郵箱授權(quán)碼,請(qǐng)看本文最后教程 mail_license = "********" # 收件人郵箱,可以為多個(gè)收件人 mail_receivers = ["******@qq.com","******@outlook.com"] mm = MIMEMultipart('related') # 郵件正文內(nèi)容 body_content = """你好,這是一個(gè)測(cè)試郵件!""" # 構(gòu)造文本,參數(shù)1:正文內(nèi)容,參數(shù)2:文本格式,參數(shù)3:編碼方式 message_text = MIMEText(body_content,"plain","utf-8") # 向MIMEMultipart對(duì)象中添加文本對(duì)象 mm.attach(message_text) # 創(chuàng)建SMTP對(duì)象 stp = smtplib.SMTP() # 設(shè)置發(fā)件人郵箱的域名和端口,端口地址為25 stp.connect(mail_host, 25) # set_debuglevel(1)可以打印出和SMTP服務(wù)器交互的所有信息 stp.set_debuglevel(1) # 登錄郵箱,傳遞參數(shù)1:郵箱地址,參數(shù)2:郵箱授權(quán)碼 stp.login(mail_sender,mail_license) # 發(fā)送郵件,傳遞參數(shù)1:發(fā)件人郵箱地址,參數(shù)2:收件人郵箱地址,參數(shù)3:把郵件內(nèi)容格式改為str stp.sendmail(mail_sender, mail_receivers, mm.as_string()) print("郵件發(fā)送成功") # 關(guān)閉SMTP對(duì)象 stp.quit()
4、Python處理數(shù)據(jù)庫(kù)
數(shù)據(jù)庫(kù)是我們常用的辦公應(yīng)用,Python中有各種數(shù)據(jù)庫(kù)驅(qū)動(dòng)接口包,支持對(duì)數(shù)據(jù)庫(kù)的增刪改查、運(yùn)維管理工作。比如說pymysql包對(duì)應(yīng)MySQL、psycopg2包對(duì)應(yīng)PostgreSQL、pymssql包對(duì)應(yīng)sqlserver、cxoracle包對(duì)應(yīng)Oracle、PyMongo包對(duì)應(yīng)MongoDB等等。
對(duì)MySQL的連接查詢
import pymysql # 打開數(shù)據(jù)庫(kù)連接 db = pymysql.connect(host='localhost', user='testuser', password='test123', database='TESTDB') # 使用 cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象 cursor cursor = db.cursor() # 使用 execute() 方法執(zhí)行 SQL 查詢 cursor.execute("SELECT VERSION()") # 使用 fetchone() 方法獲取單條數(shù)據(jù). data = cursor.fetchone() print ("Database version : %s " % data) # 關(guān)閉數(shù)據(jù)庫(kù)連接 db.close()
5、Python處理批量文件
對(duì)很多辦公場(chǎng)景來說,批量處理文件一直是個(gè)臟活累活,Python可以幫你脫離苦海。Python中有很多處理系統(tǒng)文件的包,比如sys、os、shutil、glob、path.py等等。
批量刪除不同文件夾下的同名文件夾
import os,shutil import sys import numpy as np def arrange_file(dir_path0): for dirpath,dirnames,filenames in os.walk(dir_path0): if 'my_result' in dirpath: # print(dirpath) shutil.rmtree(dirpath)
批量修改文件后綴名
import os def file_rename(): path = input("請(qǐng)輸入你需要修改的目錄(格式如'F:\\test'):") old_suffix = input('請(qǐng)輸入你需要修改的后綴(需要加點(diǎn).):') new_suffix = input('請(qǐng)輸入你要改成的后綴(需要加點(diǎn).):') file_list = os.listdir(path) for file in file_list: old_dir = os.path.join(path, file) print('當(dāng)前文件:', file) if os.path.isdir(old_dir): continue if old_suffix != os.path.splitext(file)[1]: continue filename = os.path.splitext(file)[0] new_dir = os.path.join(path, filename + new_suffix) os.rename(old_dir, new_dir) if __name__ == '__main__': file_rename()
6、Python控制鼠標(biāo)
這是很多人的需求,實(shí)現(xiàn)對(duì)鼠標(biāo)的自動(dòng)控制,去做一些流水線的工作,比如軟件測(cè)試。
Python有個(gè)pyautogui庫(kù)可以任意地去控制你的鼠標(biāo)。
控制鼠標(biāo)左擊/右擊/雙擊函數(shù)以及測(cè)試源碼
# 獲取鼠標(biāo)位置 import pyautogui as pg try: while True: x, y = pg.position() print(str(x) + " " + str(y)) #輸出鼠標(biāo)位置 if 1746 < x < 1800 and 2 < y < 33: pg.click()#左鍵單擊 if 1200 < x < 1270 and 600 < y < 620: pg.click(button='right')#右鍵單擊 if 1646 < x < 1700 and 2 < y < 33: pg.doubleClick()#左鍵雙擊 except KeyboardInterrupt: print("\n")
7、Python控制鍵盤
同樣的,Python也可以通過pyautogui控制鍵盤。
鍵盤寫入
import pyautogui #typewrite()無法輸入中文內(nèi)容,中英文混合的只能輸入英文 #interval設(shè)置文本輸入速度,默認(rèn)值為0 pyautogui.typewrite('你好,world!',interval=0.5)
8、Python壓縮文件
壓縮文件是辦公中常見的操作,一般壓縮會(huì)使用壓縮軟件,需要手動(dòng)操作。
Python中有很多包支持文件壓縮,可以讓你自動(dòng)化壓縮或者解壓縮本地文件,或者將內(nèi)存中的分析結(jié)果進(jìn)行打包。比如zipfile、zlib、tarfile等可以實(shí)現(xiàn)對(duì).zip、.rar、.7z等壓縮文件格式的操作。
壓縮文件
import zipfile try: with zipfile.ZipFile("c://test.zip",mode="w") as f: f.write("c://test.txt") #寫入壓縮文件,會(huì)把壓縮文件中的原有覆蓋 except Exception as e: print("異常對(duì)象的類型是:%s"%type(e)) print("異常對(duì)象的內(nèi)容是:%s"%e) finally: f.close()
解壓文件
import zipfile try: with zipfile.ZipFile("c://test.zip",mode="a") as f: f.extractall("c://",pwd=b"root") ##將文件解壓到指定目錄,解壓密碼為root except Exception as e: print("異常對(duì)象的類型是:%s"%type(e)) print("異常對(duì)象的內(nèi)容是:%s"%e) finally: f.close()
9、Python爬取網(wǎng)絡(luò)數(shù)據(jù)
python爬蟲應(yīng)該是最受歡迎的功能,也是廣大Python愛好者們?nèi)肟拥闹饕脑颉?/p>
Python中有非常多的包支持爬蟲,而爬蟲包又分為抓取、解析兩種。
比如說requests、urllib這種是網(wǎng)絡(luò)數(shù)據(jù)請(qǐng)求工具,也就是抓取包;xpath、re、bs4這種會(huì)對(duì)抓取下來的網(wǎng)頁(yè)內(nèi)容進(jìn)行解析,稱為解析包。
爬取百度首頁(yè)圖片,并保存到本地
# 導(dǎo)入urlopen from urllib.request import urlopen # 導(dǎo)入BeautifulSoup from bs4 import BeautifulSoup as bf # 導(dǎo)入urlretrieve函數(shù),用于下載圖片 from urllib.request import urlretrieve # 請(qǐng)求獲取HTML html = urlopen("http://www.baidu.com/") # 用BeautifulSoup解析html obj = bf(html.read(),'html.parser') # 從標(biāo)簽head、title里提取標(biāo)題 title = obj.head.title # 只提取logo圖片的信息 logo_pic_info = obj.find_all('img',class_="index-logo-src") # 提取logo圖片的鏈接 logo_url = "https:"+logo_pic_info[0]['src'] # 使用urlretrieve下載圖片 urlretrieve(logo_url, 'logo.png')
10、Python處理圖片圖表
圖片處理、圖表可視化涉及到圖像處理,這也是Python的強(qiáng)項(xiàng),現(xiàn)在諸如圖像識(shí)別、計(jì)算機(jī)視覺等前沿領(lǐng)域也都會(huì)用到Python。
在Python中處理圖像的包有scikit Image、PIL、OpenCV等,處理圖表的包有matplotlib、plotly、seaborn等。
對(duì)圖片進(jìn)行黑白化處理
from PIL import Image from PIL import ImageEnhance img_main = Image.open(u'E:/login1.png') img_main = img_main.convert('L') threshold1 = 138 table1 = [] for i in range(256): if i < threshold1: table1.append(0) else: table1.append(1) img_main = img_main.point(table1, "1") img_main.save(u'E:/login3.png')
生成統(tǒng)計(jì)圖表
import numpy as np import matplotlib.pyplot as plt N = 5 menMeans = (20, 35, 30, 35, 27) womenMeans = (25, 32, 34, 20, 25) menStd = (2, 3, 4, 1, 2) womenStd = (3, 5, 2, 3, 3) ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars: can also be len(x) sequence p1 = plt.bar(ind, menMeans, width, yerr=menStd) p2 = plt.bar(ind, womenMeans, width, bottom=menMeans, yerr=womenStd) plt.ylabel('Scores') plt.title('Scores by group and gender') plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5')) plt.yticks(np.arange(0, 81, 10)) plt.legend((p1[0], p2[0]), ('Men', 'Women')) plt.show()
小結(jié)
總之Python會(huì)成為大眾化的編程語(yǔ)言,幫助到更多需要的人,更多關(guān)于Python辦公自動(dòng)化處理的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
如何利用python實(shí)現(xiàn)詞頻統(tǒng)計(jì)功能
詞頻統(tǒng)計(jì)用途很廣泛,比如我們統(tǒng)計(jì)某篇文章中的用詞頻率,網(wǎng)絡(luò)熱點(diǎn)詞匯,再比如起名排行榜呀、熱門旅游景點(diǎn)排行榜呀什么的,其實(shí)也都可以套用,這篇文章主要給大家介紹了關(guān)于如何利用python實(shí)現(xiàn)詞頻統(tǒng)計(jì)功能的相關(guān)資料,需要的朋友可以參考下2021-10-10編寫Python腳本抓取網(wǎng)絡(luò)小說來制作自己的閱讀器
這篇文章主要介紹了編寫Python腳本抓取網(wǎng)絡(luò)小說來制作自己的閱讀器的方法,包括對(duì)小說的章節(jié)排列等方面的優(yōu)化,對(duì)于Python學(xué)習(xí)者來說非常具有實(shí)踐意義!需要的朋友可以參考下2015-08-08Python解析命令行讀取參數(shù)--argparse模塊使用方法
這篇文章主要介紹了Python解析命令行讀取參數(shù)--argparse模塊使用方法,需要的朋友可以參考下2018-01-01老生常談Python startswith()函數(shù)與endswith函數(shù)
下面小編就為大家?guī)硪黄仙U凱ython startswith()函數(shù)與endswith函數(shù)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-09-09PyQt5 實(shí)現(xiàn)字體大小自適應(yīng)分辨率的方法
今天小編就為大家分享一篇PyQt5 實(shí)現(xiàn)字體大小自適應(yīng)分辨率的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-06-06Python中的模式匹配庫(kù)Pampy使用實(shí)例解析
這篇文章主要為大家介紹了Python中的模式匹配庫(kù)Pampy使用實(shí)例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01