在程式設計世界裡,Python已經是名副其實的網紅了。
曾經一個學語言的研究生,問我怎麼學Python,因為他們課程論文裡需要用到文字分析,用Python來跑資料。我和他說,你看兩天語法,就可以上手開幹,不會的再查資料。後來這位同學半個月就用Python把論文資料搞好了。
所以Python最大優勢在於容易學,門檻比Java、C++低非常多,給非程式設計師群體提供了用程式碼幹活的可能性。當然Python能成為大眾程式設計工具,不光光是因為易學,還因為Python有成千上萬的工具包,遍佈各行各業。
舉10幾個辦公自動化常見的例子,Python都能高效處理。
1、Python處理Excel資料
可以使用pandas、xlwings、openpyxl等包來對Excel進行增刪改查、格式調整等操作,甚至可以使用Python函式來對excel資料進行分析。
讀取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等包可以輕鬆實現這些需求。
提取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] #指定頁碼
table1 = page01.extract_table()#提取單個表格
# table2 = page01.extract_tables()#提取多個表格
print(table1)
3、Python處理Email
在Python中可以使用smtplib配合email庫,來實現郵件的自動化傳輸,非常方便。
import smtplib
import email
# 負責將多個物件集合起來
from email.mime.multipart import MIMEMultipart
from email.header import Header
# SMTP伺服器,這裡使用谷歌郵箱
mail_host = "smtp.gmail.com"
# 發件人郵箱
mail_sender = "******@gmail.com"
# 郵箱授權碼,注意這裡不是郵箱密碼,如何獲取郵箱授權碼,請看本文最後教程
mail_license = "********"
# 收件人郵箱,可以為多個收件人
mail_receivers = ["******@qq.com","******@outlook.com"]
mm = MIMEMultipart('related')
# 郵件正文內容
body_content = """你好,這是一個測試郵件!"""
# 構造文字,引數1:正文內容,引數2:文字格式,引數3:編碼方式
message_text = MIMEText(body_content,"plain","utf-8")
# 向MIMEMultipart物件中新增文字物件
mm.attach(message_text)
# 建立SMTP物件
stp = smtplib.SMTP()
# 設定發件人郵箱的域名和埠,埠地址為25
stp.connect(mail_host, 25)
# set_debuglevel(1)可以打印出和SMTP伺服器互動的所有資訊
stp.set_debuglevel(1)
# 登入郵箱,傳遞引數1:郵箱地址,引數2:郵箱授權碼
stp.login(mail_sender,mail_license)
# 傳送郵件,傳遞引數1:發件人郵箱地址,引數2:收件人郵箱地址,引數3:把郵件內容格式改為str
stp.sendmail(mail_sender, mail_receivers, mm.as_string())
print("郵件傳送成功")
# 關閉SMTP物件
stp.quit()
4、Python處理資料庫
資料庫是我們常用的辦公應用,Python中有各種資料庫驅動介面包,支援對資料庫的增刪改查、運維管理工作。比如說pymysql包對應MySQL、psycopg2包對應PostgreSQL、pymssql包對應sqlserver、cxoracle包對應Oracle、PyMongo包對應MongoDB等等。
對MySQL的連線查詢
import pymysql
# 開啟資料庫連線
db = pymysql.connect(host='localhost',
user='testuser',
password='test123',
database='TESTDB')
# 使用 cursor() 方法建立一個遊標物件 cursor
cursor = db.cursor()
# 使用 execute() 方法執行 SQL 查詢
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法獲取單條資料.
data = cursor.fetchone()
print ("Database version : %s " % data)
# 關閉資料庫連線
db.close()
5、Python處理批次檔案
對很多辦公場景來說,批次處理檔案一直是個髒活累活,Python可以幫你脫離苦海。Python中有很多處理系統檔案的包,比如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("請輸入你需要修改的目錄(格式如'F:\\test'):")
old_suffix = input('請輸入你需要修改的字尾(需要加點.):')
new_suffix = input('請輸入你要改成的字尾(需要加點.):')
file_list = os.listdir(path)
for file in file_list:
old_dir = os.path.join(path, file)
print('當前檔案:', 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控制滑鼠
這是很多人的需求,實現對滑鼠的自動控制,去做一些流水線的工作,比如軟體測試。
Python有個pyautogui庫可以任意地去控制你的滑鼠。
控制滑鼠左擊/右擊/雙擊函式以及測試原始碼
# 獲取滑鼠位置
import pyautogui as pg
try:
while True:
x, y = pg.position()
print(str(x) + " " + str(y)) #輸出滑鼠位置
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()無法輸入中文內容,中英文混合的只能輸入英文
#interval設定文字輸入速度,預設值為0
pyautogui.typewrite('你好,world!',interval=0.5)
8、Python壓縮檔案
壓縮檔案是辦公中常見的操作,一般壓縮會使用壓縮軟體,需要手動操作。
Python中有很多包支援檔案壓縮,可以讓你自動化壓縮或者解壓縮本地檔案,或者將記憶體中的分析結果進行打包。比如zipfile、zlib、tarfile等可以實現對.zip、.rar、.7z等壓縮檔案格式的操作。
壓縮檔案
import zipfile
try:
with zipfile.ZipFile("c://test.zip",mode="w") as f:
f.write("c://test.txt") #寫入壓縮檔案,會把壓縮檔案中的原有覆蓋
except Exception as e:
print("異常物件的型別是:%s"%type(e))
print("異常物件的內容是:%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("異常物件的型別是:%s"%type(e))
print("異常物件的內容是:%s"%e)
finally:
f.close()
9、Python爬取網路資料
python爬蟲應該是最受歡迎的功能,也是廣大Python愛好者們入坑的主要的原因。
Python中有非常多的包支援爬蟲,而爬蟲包又分為抓取、解析兩種。
比如說requests、urllib這種是網路資料請求工具,也就是抓取包;xpath、re、bs4這種會對抓取下來的網頁內容進行解析,稱為解析包。
爬取Bing首頁圖片,並儲存到本地
# 匯入urlopen
from urllib.request import urlopen
# 匯入BeautifulSoup
from bs4 import BeautifulSoup as bf
# 匯入urlretrieve函式,用於下載圖片
from urllib.request import urlretrieve
# 請求獲取HTML
html = urlopen("http://www.bing.com/")
# 用BeautifulSoup解析html
obj = bf(html.read(),'html.parser')
# 從標籤head、title裡提取標題
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的強項,現在諸如影象識別、計算機視覺等前沿領域也都會用到Python。
在Python中處理影象的包有scikit Image、PIL、OpenCV等,處理圖表的包有matplotlib、plotly、seaborn等。
對圖片進行黑白化處理
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')
生成統計圖表
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()
小結
總之Python會成為大眾化的程式語言,幫助到更多需要的人。
文章來源:Python大數據分析
原文連結:https://mp.weixin.qq.com/s/MBVLnCnQFIipsDgT27N7yw
※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※
我是「數據分析那些事」。常年分享數據分析乾貨,不定期分享好用的職場技能工具。各位也可以關注我的Facebook,按讚我的臉書並私訊「10」,送你十週入門數據分析電子書唷!期待你與我互動起來~
文章推薦
◆跟資料打交道的人都得會的這8種資料模型,滿足工作中95%的需求
回顧十週入門數據分析系列文:
關注數據君的臉書:
我是「數據分析那些事」。常年分享數據分析乾貨,不定期分享好用的職場技能工具。按贊我的臉書,會有豐富資料包贈送唷!