1、Python处理Excel数据

import xlwings as xwwb = xw.Book() # this will create a new workbookwb = xw.Book('FileName.xlsx') # connect to a file that is open or in the current working directorywb = xw.Book(r'C:\path\to\file.xlsx') # on Windows: use raw strings to escape backslashes
import matplotlib.pyplot as pltimport xlwings as xwfig = plt.figure()plt.plot([1, 2, 3])sheet = xw.Book().sheets[0]sheet.pictures.add(fig, name='MyPlot', update=True)

2、Python处理PDF文本

import PyPDF2pdfFile = open('example.pdf','rb')pdfReader = PyPDF2.PdfFileReader(pdfFile)print(pdfReader.numPages)page = pdfReader.getPage(0)print(page.extractText())pdfFile.close()
# 提取pdf表格import pdfplumberwith pdfplumber.open("example.pdf") as pdf: page01 = pdf.pages[0] #指定页码 table1 = page01.extract_table()#提取单个表格 # table2 = page01.extract_tables()#提取多个表格 print(table1)
3、Python处理Email
import smtplibimport email# 负责将多个对象集合起来from email.mime.multipart import MIMEMultipartfrom email.header import Header# SMTP服务器,这里使用163邮箱mail_host = "smtp.163.com"# 发件人邮箱mail_sender = "******@163.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()# 设置发件人邮箱的域名和端口,端口地址为25stp.connect(mail_host, 25) # set_debuglevel(1)可以打印出和SMTP服务器交互的所有信息stp.set_debuglevel(1)# 登录邮箱,传递参数1:邮箱地址,参数2:邮箱授权码stp.login(mail_sender,mail_license)# 发送邮件,传递参数1:发件人邮箱地址,参数2:收件人邮箱地址,参数3:把邮件内容格式改为strstp.sendmail(mail_sender, mail_receivers, mm.as_string())print("邮件发送成功")# 关闭SMTP对象stp.quit()
4、Python处理数据库
import pymysql # 打开数据库连接db = pymysql.connect(host='localhost', user='testuser', password='test123', database='TESTDB') # 使用 cursor() 方法创建一个游标对象 cursorcursor = db.cursor()# 使用 execute() 方法执行 SQL 查询 cursor.execute("SELECT VERSION()")# 使用 fetchone() 方法获取单条数据.data = cursor.fetchone()print ("Database version : %s " % data)# 关闭数据库连接db.close()
5、Python处理批量文件
import os,shutilimport sysimport numpy as npdef arrange_file(dir_path0): for dirpath,dirnames,filenames in os.walk(dir_path0): if 'my_result' in dirpath: # print(dirpath) shutil.rmtree(dirpath)
import osdef 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控制鼠标
# 获取鼠标位置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控制键盘
import pyautogui#typewrite()无法输入中文内容,中英文混合的只能输入英文#interval设置文本输入速度,默认值为0pyautogui.typewrite('你好,world!',interval=0.5)
8、Python压缩文件
import zipfiletry: 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 zipfiletry: with zipfile.ZipFile("c://test.zip",mode="a") as f: f.extractall("c://",pwd=b"root") ##将文件解压到指定目录,解压密码为rootexcept Exception as e: print("异常对象的类型是:%s"%type(e)) print("异常对象的内容是:%s"%e)finally: f.close()
9、Python爬取网络数据
# 导入urlopenfrom urllib.request import urlopen# 导入BeautifulSoupfrom bs4 import BeautifulSoup as bf# 导入urlretrieve函数,用于下载图片from urllib.request import urlretrieve# 请求获取HTMLhtml = urlopen("http://www.baidu.com/")# 用BeautifulSoup解析htmlobj = 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处理图片图表
from PIL import Imagefrom PIL import ImageEnhanceimg_main = Image.open(u'E:/login1.png')img_main = img_main.convert('L')threshold1 = 138table1 = []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 npimport matplotlib.pyplot as pltN = 5menMeans = (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 groupswidth = 0.35 # the width of the bars: can also be len(x) sequencep1 = 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语法基础,再到框架,从基础到深入,还是很容易入门的。至于视频,网络上实际上有一大堆,我这边是学长给我的珍藏版,应该是搜索不到,如果你需要,当然我也可以免费分享给你。需要学习的小伙伴可以私信02 获取~
Linux基础

Python基础

面向对象

项目飞机大战


相关推荐阅读: