当前位置: 首页 > 科技观察

五个有趣的Python脚本

时间:2023-03-13 20:15:41 科技观察

Python可以玩很多方向,爬虫、预测分析、GUI、自动化、图像处理、可视化等,可能只需要十几行代码就可以实现很酷的功能。因为Python是一种动态脚本语言,代码逻辑比Java简单很多,实现同样的功能用的代码更少。而且Python生态中有很多第三方工具库,所有的功能都封装在包中,复杂的功能只需要调用接口即可。这里有几个简单好玩的脚本例子,初学者可以跟着代码写,快速掌握python语法。1、使用PIL、Matplotlib、Numpy修复模糊老照片asarray(img)flat=img.flatten()defget_histogram(image,bins):histogram=np.zeros(bins)对于图像中的像素:histogram[pixel]+=1returnhistogramhist=get_histogram(flat,256)cs=np.cumsum(hist)nj=(cs-cs.min())*255N=cs.max()-cs.min()cs=nj/Ncs=cs.astype('uint8')img_new=cs[平坦]img_new=np.reshape(img_new,img.shape)fig=plt.figure()fig.set_figheight(15)fig.set_figwidth(15)fig.add_subplot(1,2,1)plt.imshow(img,cmap='gray')plt.title("Image'Before'ContrastAdjustment")fig.add_subplot(1,2,2)plt.imshow(img_new,cmap='gray')plt.title("Image'After'对比度调整")filename=os.path.basename(img_path)plt.show()2.批量压缩文件,使用zipfile库importosimportzipfilefromrandomimportrandomdefzip_dir(path,zip_handler):对于os.walk(path)中的根、目录、文件:对于文件中的文件:zip_handler.write(os.path.join(root,file))if__name__=='__main__':to_zip=input("""Enter您要压缩的文件夹的名称(注意:文件夹名称不应包含空格)>""")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'FileSavedas{zip_file_name}')3、使用tkinter制作计算器GUItkinter是python自带的GUI库,适合初学者练习手创小软件importtkinterastkroot=tk.Tk()root.title("StandardCalculator")root.resizable(0,0)e=tk.Entry(root,width=35,bg='#f0ffff',fg='black',borderwidth=5,justify='right',font='Calibri15')e.grid(行=0,列=0,columnspan=3,padx=12,pady=12)defbuttonClick(num):temp=e.get()e.delete(0,tk.END)e.insert(0,temp+num)defbuttonClear():e.delete(0,tk.END)4.将PDF转换为Word文件使用pdf2docx库将PDF文件从pdf2docximportConverterimportosimportsyspdf=input("Enterthepathtoyourfile:")assertos.path.exists(pdf),"Filenotfoundat,"+str(pdf)f=open(pdf,'r+')doc_name_choice=input("Doyouwanttogiveacustomnametoyourfile?(Y/N)")if(doc_name_choice=='Y'ordoc_name_choice=='y'):doc_name=input("Enterthecustom名称:")+".docx"其他:pdf_name=os.path.basename(pdf)doc_name=os.path.splitext(pdf_name)[0]+".docx"cv=Converter(pdf)path=os.path.dirname(pdf)cv.convert(os.path.join(path,"",doc_name),start=0,end=None)print("Worddoccreated!")cv.close()5、Python自动发送邮件使用smtplib和email库实现脚本发送邮件importsmtplibimportemailfromemail.mime.textimportMIMETextfromemail.mime.imageimportMIMEImagefromemail.mime.multipartimportMIMEMultipartfromemail.headerimportHeadermail_host="smtp.163.com"mail_sender="******@163.com"mail_license="********"mail_receivers=["******@qq.com","******@outlook.com"]mm=MIMEMultipart('相关')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="""你好,这是一个测试邮件!"""message_text=MIMEText(body_content,"plain","utf-8")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"]='依恋;filename="sample.xlsx"'mm.attach(atta)stp=smtplib.SMTP()stp.connect(mail_host,25)stp.set_debuglevel(1)stp.login(mail_sender,mail_license)stp.sendmail(mail_sender,mail_receivers,mm.as_string())print("邮件发送成功")stp.quit()SummaryPython还有还有很多好玩的小脚本,大家可以根据自己的场景来写,也可以使用现成的第三方库