5个有趣的Python脚本(python脚本例子)
off999 2024-10-11 14:04 64 浏览 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还有很多好玩的小脚本,你可以根据自己的场景来编写,也可以使用现成的第三方库。
相关推荐
- 免费wifi上网(怎样打开免费wifi上网)
-
免费wifi并非完全真实存在。免费wifi虽然在许多公共场所提供,但并非完全免费。通常情况下,提供免费wifi的场所会要求用户进行一些操作,如填写个人信息、观看广告或接受其他形式的付费。这些操作可能会...
- 本机ip查询地址定位查询(本机ip地址查询位置)
-
1.地理定位信息。具体的位置是可以通过ip地址查询得出来的。因此,对于当下电信诈骗或者一些网络虚拟的情况下,这样的查询方式是很重要的,也是很容易得出来信息的。只有这样,才能够在定位方面更加精准可靠一点...
- wifi万能密码破解器(wifi万能密码破解版)
-
万能钥匙主要的作用是分享与被分享的关系,你所用万能钥匙一件查询和破解的都是别人分享的密码,不是万能钥匙破解的作用,真正能破解的只是那些密码简单的,比如12345678或者豹子数比如88888888和1...
- win8的稳定性(win8稳定还是win10稳定)
-
如果是玩游戏Win7相对win7稳定一些,能兼容大部分的游戏。其它的应该各有千秋,具体上可以从如下几点了解:1、Win8相对Win7开机更快,内存管理更高效,HTML5支持更好,兼容暂时落后。2、Wi...
- 怎么切任务管理器(任务管理)
-
任务管理器切换方法如下1.先按WIN+X,再按T,即可呼出任务管理器2.同时按Ctrl+Shift+Esc,即可呼出任务管理器。3.同时按Ctrl+Alt+Del,在跳转的界面里...
- windows激活无法连接到组织网络
-
1、在桌面新建一个文本文档,把代码复制进去2、点击文件选择“另存为”,在弹出的界面中,将保存位置选择在桌面,保存类型改为所有文件,文件名改为.bat格式的文件,然后点击“保存”按钮; 3、右...
-
- 企业邮箱注册申请流程(企业邮箱怎么注册申请)
-
点击进入官网,进入邮箱后,点击下方的企业邮箱,开通邮箱有两个版本,一个是免费版,一个是专业版,这边点击免费版的立即开通,弹出的界面,输入账号、密码以及手机号码,输入验证码。扩展知识:企业邮箱特点1、便于管理企业可以自行设定管理员来分配和管理...
-
2026-01-14 13:43 off999
-
- window截图快捷键(windows自带截屏的方法)
-
1、按Prtsc键截图这样获取的是整个电脑屏幕的内容,按Prtsc键后,可以直接打开画图工具,接粘贴使用。也可以粘贴在QQ聊天框或者Word文档中,之后再选择保存即可。2、按Ctrl+Prtsc键截图截屏获得的内容也是整个电脑屏幕,与上面的...
-
2026-01-14 13:15 off999
- win10一定要创建账户吗(win10需要创建microsoft账户吗)
-
win10系统安装不需要申请微软账号。如果是在安装win10的过程中,则使用本地账户登录,从安装主要步骤完成之后进入后续设置阶段开始,步骤如下:1、首先就是要输入产品密钥,或者点击左下角“以后再说”。...
- win10显示已禁用输入法(w10系统已禁用输入法)
-
在使用win10的过程中,有时候利用第三方软件过度优化开机启动项目就容易导致win10无法打开输入法问题,这个情况是由于ctfmon程序无法正常启动所致,一般表现在电脑桌面右下角显示已禁用ime的提示...
- windows pad(windowspad官方网站入口)
-
平板电脑安装windows方法如下1、首先,下载并安装U启动PE制作工具,这里要特别注意的是,要下载装机版的。2、点开PE制作工具的主界面,插入U盘,等待U盘被制作工具识别出来后。3、点击归还空间,然...
- 为什么电脑一开机就死机(为什么电脑一开机就死机重启)
-
一、软件问题: 1、导致死机的一个重要原因就是病毒程序的入侵。大家都知道,病毒程序是一种会破坏计算机软件系统,并占用极大的系统资源的一种恶意攻击程序,它会给计算机本身的软件造成很大的伤害。死机时的首...
- 0x0000007a蓝屏解救方法win7
-
0x0000007A说明是内存或虚拟内存(硬盘)的问题,你可以按顺序尝试如下操作:1、更改虚拟内存页面文件位置:我的电脑→右键→属性→高级→性能设置→高级→虚拟内存更改→取消原来选择的驱动器(默认在C...
- 系统小说排行榜完本经典之作
-
超级兑换系统超级修仙超级客栈系统貌似高手在异界重生之修仙系统超级修仙系统异界之兑换成圣(贱圣VS奸神)+超级兑换(火山飞狐)+穿越之无敌兑换(开心小帅)+兑换器修仙(轻舞流芒)+...
- 手机能修复u盘吗(手机修复u盘工具下载)
-
1.在手机上可以恢复u盘,当手机SD卡或U盘插入电脑中时,如果提示“文件或目录损坏且无法读取”的信息时,我们首先需要对手机SD卡或U盘进行目录修复操作。插入待修复的U盘,打开“我的电脑”,找到Sd卡...
欢迎 你 发表评论:
- 一周热门
-
-
抖音上好看的小姐姐,Python给你都下载了
-
全网最简单易懂!495页Python漫画教程,高清PDF版免费下载
-
飞牛NAS部署TVGate Docker项目,实现内网一键转发、代理、jx
-
Python 3.14 的 UUIDv6/v7/v8 上新,别再用 uuid4 () 啦!
-
python入门到脱坑 输入与输出—str()函数
-
宝塔面板如何添加免费waf防火墙?(宝塔面板开启https)
-
Python三目运算基础与进阶_python三目运算符判断三个变量
-
(新版)Python 分布式爬虫与 JS 逆向进阶实战吾爱分享
-
失业程序员复习python笔记——条件与循环
-
系统u盘安装(win11系统u盘安装)
-
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)
