5个有趣的Python脚本(python脚本例子)
ztj100 2024-11-08 15:06 23 浏览 0 评论
Python可以玩的方向有很多,比如爬虫、预测分析、GUI、自动化、图像处理、可视化等等,可能只需要十几行代码就能实现酷炫的功能。
因为Python是动态脚本语言,所以代码逻辑比Java要简要很多,实现同样的功能少写很多代码。而且Python生态有众多的第三方工具库,把功能都封装在包里,只需要你调用接口,就能使用复杂的功能。
下面举几个简单好玩的脚本例子,初学者可以照着代码写写,能快速掌握python语法。
1、使用PIL、Matplotlib、Numpy对模糊老照片进行修复
# encoding=utf-8
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import os.path
# 读取图片
img_path = "E:\\test.jpg"
img = Image.open(img_path)
# 图像转化为numpy数组
img = np.asarray(img)
flat = img.flatten()
# 创建函数
def get_histogram(image, bins):
# array with size of bins, set to zeros
histogram = np.zeros(bins)
# loop through pixels and sum up counts of pixels
for pixel in image:
histogram[pixel] += 1
# return our final result
return histogram
# execute our histogram function
hist = get_histogram(flat, 256)
# execute the fn
cs = np.cumsum(hist)
# numerator & denomenator
nj = (cs - cs.min()) * 255
N = cs.max() - cs.min()
# re-normalize the cumsum
cs = nj / N
# cast it back to uint8 since we can't use floating point values in images
cs = cs.astype('uint8')
# get the value from cumulative sum for every index in flat, and set that as img_new
img_new = cs[flat]
# put array back into original shape since we flattened it
img_new = np.reshape(img_new, img.shape)
# set up side-by-side image display
fig = plt.figure()
fig.set_figheight(15)
fig.set_figwidth(15)
# display the real image
fig.add_subplot(1, 2, 1)
plt.imshow(img, cmap='gray')
plt.title("Image 'Before' Contrast Adjustment")
# display the new image
fig.add_subplot(1, 2, 2)
plt.imshow(img_new, cmap='gray')
plt.title("Image 'After' Contrast Adjustment")
filename = os.path.basename(img_path)
# plt.savefig("E:\\" + filename)
plt.show()
2、将文件批量压缩,使用zipfile库
import os
import zipfile
from random import randrange
def zip_dir(path, zip_handler):
for root, dirs, files in os.walk(path):
for file in files:
zip_handler.write(os.path.join(root, file))
if __name__ == '__main__':
to_zip = input("""
Enter the name of the folder you want to zip
(N.B.: The folder name should not contain blank spaces)
>
""")
to_zip = to_zip.strip() + "/"
zip_file_name = f'zip{randrange(0,10000)}.zip'
zip_file = zipfile.ZipFile(zip_file_name, 'w', zipfile.ZIP_DEFLATED)
zip_dir(to_zip, zip_file)
zip_file.close()
print(f'File Saved as {zip_file_name}')
3、使用tkinter制作计算器GUI
tkinter是python自带的GUI库,适合初学者练手创建小软件
import tkinter as tk
root = tk.Tk() # Main box window
root.title("Standard Calculator") # Title shown at the title bar
root.resizable(0, 0) # disabling the resizeing of the window
# Creating an entry field:
e = tk.Entry(root,
width=35,
bg='#f0ffff',
fg='black',
borderwidth=5,
justify='right',
font='Calibri 15')
e.grid(row=0, column=0, columnspan=3, padx=12, pady=12)
def buttonClick(num): # function for clicking
temp = e.get(
) # temporary varibale to store the current input in the screen
e.delete(0, tk.END) # clearing the screen from index 0 to END
e.insert(0, temp + num) # inserting the incoming number input
def buttonClear(): # function for clearing
e.delete(0, tk.END)
# 代码过长,部分略
4、PDF转换为Word文件
使用pdf2docx库,可以将PDF文件转为Word格式
from pdf2docx import Converter
import os
import sys
# Take PDF's path as input
pdf = input("Enter the path to your file: ")
assert os.path.exists(pdf), "File not found at, "+str(pdf)
f = open(pdf,'r+')
#Ask for custom name for the word doc
doc_name_choice = input("Do you want to give a custom name to your file ?(Y/N)")
if(doc_name_choice == 'Y' or doc_name_choice == 'y'):
# User input
doc_name = input("Enter the custom name : ")+".docx"
else:
# Use the same name as pdf
# Get the file name from the path provided by the user
pdf_name = os.path.basename(pdf)
# Get the name without the extension .pdf
doc_name = os.path.splitext(pdf_name)[0] + ".docx"
# Convert PDF to Word
cv = Converter(pdf)
#Path to the directory
path = os.path.dirname(pdf)
cv.convert(os.path.join(path, "", doc_name) , start=0, end=None)
print("Word doc created!")
cv.close()
5、Python自动发送邮件
使用smtplib和email库可以实现脚本发送邮件
import smtplib
import email
# 负责构造文本
from email.mime.text import MIMEText
# 负责构造图片
from email.mime.image import MIMEImage
# 负责将多个对象集合起来
from email.mime.multipart import MIMEMultipart
from 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')
# 邮件主题
subject_content = """Python邮件测试"""
# 设置发送者,注意严格遵守格式,里面邮箱为发件人邮箱
mm["From"] = "sender_name<******@163.com>"
# 设置接受者,注意严格遵守格式,里面邮箱为接受者邮箱
mm["To"] = "receiver_1_name<******@qq.com>,receiver_2_name<******@outlook.com>"
# 设置邮件主题
mm["Subject"] = Header(subject_content,'utf-8')
# 邮件正文内容
body_content = """你好,这是一个测试邮件!"""
# 构造文本,参数1:正文内容,参数2:文本格式,参数3:编码方式
message_text = MIMEText(body_content,"plain","utf-8")
# 向MIMEMultipart对象中添加文本对象
mm.attach(message_text)
# 二进制读取图片
image_data = open('a.jpg','rb')
# 设置读取获取的二进制数据
message_image = MIMEImage(image_data.read())
# 关闭刚才打开的文件
image_data.close()
# 添加图片文件到邮件信息当中去
mm.attach(message_image)
# 构造附件
atta = MIMEText(open('sample.xlsx', 'rb').read(), 'base64', 'utf-8')
# 设置附件信息
atta["Content-Disposition"] = 'attachment; filename="sample.xlsx"'
# 添加附件到邮件信息当中去
mm.attach(atta)
# 创建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()
小结
Python还有很多好玩的小脚本,你可以根据自己的场景来编写,也可以使用现成的第三方库。
相关推荐
- 人生苦短,我要在VSCode里面用Python
-
轻沉发自浅度寺量子位出品|公众号QbitAI在程序员圈子里,VisualStudioCode(以下简称VSCode)可以说是目前最火的代码编辑器之一了。它是微软出品的一款可扩展的轻量...
- 亲测可用:Pycharm2019.3专业版永久激活教程
-
概述随着2020年的到来,又有一批Pycharm的激活码到期了,各位同仁估计也是在到处搜索激活方案,在这里,笔者为大家收录了一个永久激活的方案,亲测可用,欢迎下载尝试:免责声明本项目只做个人学习研究之...
- Python新手入门很简单(python教程入门)
-
我之前学习python走过很多的歧途,自学永远都是瞎猫碰死耗子一样,毫无头绪。后来心里一直都有一个做头条知识分享的梦,希望自己能够帮助曾经类似自己的人,于是我来了,每天更新5篇Python文章,喜欢的...
- Pycharm的设置和基本使用(pycharm运行设置)
-
这篇文章,主要是针对刚开始学习python语言,不怎么会使用pycharm的童鞋们;我来带领大家详细了解下pycharm页面及常用的一些功能,让大家能通过此篇文章能快速的开始编写python代码。一...
- 依旧是25年最拔尖的PyTorch实用教程!堪比付费级内容!
-
我真的想知道作者到底咋把PyTorch教程整得这么牛的啊?明明在内容上已经足以成为付费教材了,但作者偏要免费开源给大家学习!...
- 手把手教你 在Pytorch框架上部署和测试关键点人脸检测项目DBFace
-
这期教向大家介绍仅仅1.3M的轻量级高精度的关键点人脸检测模型DBFace,并手把手教你如何在自己的电脑端进行部署和测试运行,运行时bug解决。01.前言前段时间DBFace人脸检测库横空出世,...
- 进入Python的世界02外篇-Pycharm配置Pyqt6
-
为什么这样配置,要开发带UI的python也只能这样了,安装过程如下:一安装工具打开终端:pipinstallPyQt6PyQt6-tools二打开设置并汉化点击plugin,安装汉化插件,...
- vs code如何配置使用Anaconda(vscode调用anaconda库)
-
上一篇文章中(Anaconda使用完全指南),我们能介绍了Anaconda的安装和使用,以及如何在pycharm中配置Anaconda。本篇,将继续介绍在vscode中配置conda...
- pycharm中conda解释器无法配置(pycharm配置anaconda解释器)
-
之前用的好好的pycharm正常配置解释器突然不能用了?可以显示有这个环境然后确认后可以conda正在配置解释器,但是进度条结束后还是不成功!!试过了pycharm重启,pycharm重装,anaco...
- Volta:跨平台开发者的福音,统一前端js工具链从未如此简单!
-
我们都知道现在已经进入了Rust时代,不仅很多终端常用的工具都被rust重写了,而且现在很多前端工具也开始被Rust接手了,这不,现在就出现了一款JS工具管理工具,有了它,你可以管理多版本的js工具,...
- 开发者的福音,ElectronEgg: 新一代桌面应用开发框架
-
今天给大家介绍一个开源项目electron-egg。如果你是一个JS的前端开发人员,以前面对这项任务桌面应用开发在时,可能会感到无从下手,甚至觉得这是一项困难的挑战。ElectronEgg的出现,它能...
- 超强经得起考验的低代码开发平台Frappe
-
#挑战30天在头条写日记#开始进行管理软件的开发来讲,如果从头做起不是不可以,但选择一款免费的且经得起时间考验的低代码开发平台是非常有必要的,将大幅提升代码的质量、加快开发的效率、以及提高程序的扩展性...
- 一文带你搞懂Vue3 底层源码(vue3核心源码解析)
-
作者:妹红大大转发链接:https://mp.weixin.qq.com/s/D_PRIMAD6i225Pn-a_lzPA前言vue3出来有一段时间了。今天正式开始记录一下梗vue3.0.0-be...
- 基于小程序 DSL(微信、支付宝)的,可扩展的多端研发框架
-
Mor(发音为/mr/,类似more),是饿了么开发的一款基于小程序DSL的,可扩展的多端研发框架,使用小程序原生DSL构建,使用者只需书写一套(微信或支付宝)小程序,就可以通过Mor...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- 人生苦短,我要在VSCode里面用Python
- 亲测可用:Pycharm2019.3专业版永久激活教程
- Python新手入门很简单(python教程入门)
- Pycharm的设置和基本使用(pycharm运行设置)
- 依旧是25年最拔尖的PyTorch实用教程!堪比付费级内容!
- 手把手教你 在Pytorch框架上部署和测试关键点人脸检测项目DBFace
- 进入Python的世界02外篇-Pycharm配置Pyqt6
- vs code如何配置使用Anaconda(vscode调用anaconda库)
- pycharm中conda解释器无法配置(pycharm配置anaconda解释器)
- Volta:跨平台开发者的福音,统一前端js工具链从未如此简单!
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)
- vmware17pro最新密钥 (34)
- mysql单表最大数据量 (35)