百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

5个有趣的Python脚本(python脚本例子)

off999 2024-10-11 14:04 56 浏览 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还有很多好玩的小脚本,你可以根据自己的场景来编写,也可以使用现成的第三方库。

相关推荐

hotmail电子邮箱登录(hotmail邮箱在线登录)

***@hotmail.com1、其中***是你自己申请的邮箱的用户名。2、hotmail要写在符号@后面。3、最后加上.com,这样就是一个完整的hotmail邮箱的格式。4、比如:zhangj...

qq恢复官方网站聊天记录(qq恢复聊天记录在哪里)
  • qq恢复官方网站聊天记录(qq恢复聊天记录在哪里)
  • qq恢复官方网站聊天记录(qq恢复聊天记录在哪里)
  • qq恢复官方网站聊天记录(qq恢复聊天记录在哪里)
  • qq恢复官方网站聊天记录(qq恢复聊天记录在哪里)
win10iso文件(win10iso文件怎么安装)

安装Win10ISO系统文件需要以下步骤:1.首先需要从Microsoft官网下载Win10ISO系统文件,打开网站后选择Win10的版本、语言和架构(32位或64位),点击下载即可。2.下载...

qq邮箱登录不上去怎么回事(qq邮箱怎么登陆不上去)
  • qq邮箱登录不上去怎么回事(qq邮箱怎么登陆不上去)
  • qq邮箱登录不上去怎么回事(qq邮箱怎么登陆不上去)
  • qq邮箱登录不上去怎么回事(qq邮箱怎么登陆不上去)
  • qq邮箱登录不上去怎么回事(qq邮箱怎么登陆不上去)
英特尔显卡性能排行(英特尔显卡性能排行天梯图)

IRIS(英特尔第四/五代集成显卡)英特尔第四代集成显卡,分为HD4200/4400/4600,HD5100/5200。代号为GT2/3/3e,中文名为锐炬。hd420044004600和台式...

电脑做系统u盘启动选项(做系统开机u盘怎么选择)

操作须知:1、设置U盘启动分很多种:传统legacy机型设置、uefi新机型设置、uefi机型改legacy启动设置2、由于电脑品牌以及机型非常多,这边仅列举一部分电脑的设置方法,3、如果是uefi机...

未安装nvidia控制面板(电脑未安装nvidia控制面板)

如果你使用的是Nvidia显卡,但未安装Nvidia控制面板,则可能会遇到以下问题:1.无法进行高级显卡设置:Nvidia控制面板提供了高级显卡设置选项,例如显卡超频、显示器分辨率和刷新率、视频调整...

u盘检测不到怎么修复(u盘检查不了是什么原因)

以下是可能的解决办法:1.更换不同的USB端口。有时候电脑某个USB端口可能出现问题,试试换一个不同的端口。2.重启电脑。有时候出现问题的USB端口可能需要重启才能正常。3.插拔几次U盘。有时候...

win7 共享设置(win7共享设置详细步骤)

1.进入控制面板家庭组页打开控制面板找到网络和Internet下面的家庭组和共享选项并打开?2.进入更改高级共享设置打开以后选择更改高级共享设置功能进入?3.开启文件和打印机共享开启文件和打印机共享,...

电脑硬盘怎么装步骤图(电脑硬盘怎么装步骤图片)

1、查看硬盘的各项信息。硬盘的背面会有硬盘的存储容量以及电压,功率,转速等基本信息。2、购买到的一整块硬盘里面包括硬盘、对接线跟螺丝钉。将对接线和螺丝钉摆在一旁。3、在硬盘的上方会有两个SATA接口,...

小马win10永久激活(小马win10永久激活工具使用方法)

很简单,重装系统win7,这个可以激活的,然后根据推送升级win10,如果有强迫症可以升级以后重新安装win10系统,以后都是自动联网激活的。安全。小马激活工具win10版是小马专门为windowns...

win10开机欢迎时间太长(开机欢迎界面时间长)

win10第一个就是你系统里的垃圾太多,如果系统垃圾太多,直接清理垃圾就可以解决这个问题,第二个就是你的开机启动项过多,如果开机启动项过多,直接关闭不必要的开机启动项就可以缩短开机时间,就可以解决你...

登录126邮箱入口(登录126邮箱入口官网)

126邮箱是网易的一个免费邮箱登录入口在浏览器输入:mail.126.com浏览器进入126邮箱网站之后,即可自行登录126邮箱账号。如何在手机上登录126邮箱1、打开手机,找到并打开网易邮箱软件。2...

如何让防火墙允许某个软件(如何允许防火墙阻止访问)

1.打开电脑的开始菜单,找到控制面板选项,并点击打开。2.在打开的控制面板中,找到防火墙选项,并点击打开。3.在打开的防火墙界面中,单击左侧的允许程序通过防火墙选项。4.在跳转的界面中,选择允许通过防...

智慧工厂管理系统(智慧工厂管理系统哪家好)
智慧工厂管理系统(智慧工厂管理系统哪家好)

智慧工厂智能化系统整体的解决方案分为三个主要部分,分别是现场控制系统(FDC)、生产数据管理系统(PDM)以及工厂数字化协同平台(LCT)。其中,现场控制系统(FDC)是智慧工厂系统非常重要的核心组成部分,它是一个支持大规模互联的集群控制系...

2025-11-13 22:03 off999

取消回复欢迎 发表评论: