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

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

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

相关推荐

window截图快捷键(windows自带截屏的方法)
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卡...

怎么查电脑显卡的信息(电脑怎么查看显卡信息)

要查看电脑的显卡信息,可以按照以下步骤进行操作:1.使用快捷键Win+R打开“运行”对话框。2.在运行对话框中输入“dxdiag”并点击“确定”按钮,打开“DirectX诊断工具”。3....

电脑上找不到输入法怎么办(电脑中找不到输入法)

如果电脑上不显示输入法,您可以尝试以下解决方法:1.检查输入法设置:首先,您可以检查电脑的输入法设置。在Windows系统中,您可以点击任务栏右下角的输入法图标(一般为字母或语言标志),然后选择“显...

win10系统本地连接在哪里(window10的本地连接在哪)

要找到本地连接,可以按照以下步骤在Windows10系统中进行:1.点击“开始”菜单,然后选择“设置”(齿轮图标)。2.在设置窗口中选择“网络和Internet”选项。3.在“网络和Inter...

win10有32位版本吗(win10还有32位的吗)

64位版本好。32位的操作系统处理数据的能力较慢,支持的内存小,并且只支持基于32位的软件,不能运行64位的软件。64位的操作系统处理数据的能力较快,支持的内存较大,能运行32位的软件,也能运行6...

pdf打印机下载(pdf打印机安装程序下载)
  • pdf打印机下载(pdf打印机安装程序下载)
  • pdf打印机下载(pdf打印机安装程序下载)
  • pdf打印机下载(pdf打印机安装程序下载)
  • pdf打印机下载(pdf打印机安装程序下载)
账号密码大全真的(各种账号密码)

英雄号,是4399官方版本的账号:1973024549密码:123456这是自己的,不想玩了,送给看到的有缘人吧^o^1、默认的机顶盒密码6321,也可以进行更改,方法:首先,通过搜索“中国电信”...

windows server2019(windowsserver2019密钥激活码)

WindowsServer2019那是给服务器用的系统。服务器的作用是计算数据,而不是图像处理。所以WindowsServer2019里面精简了大量有关图形的功能。办公和打游戏是需要图像处理的...

取消回复欢迎 发表评论: