Python可以玩的方向有很多,比如爬虫、预测分析、GUI、自动化、图像处理、可视化等等,可能只需要十几行代码就能实现酷炫的功能。 因为Python是动态脚本语言,所以代码逻辑比Java要简要很多,实现同样的功能少写很多代码。而且Python生态有众多的第三方工具库,把功能都封装在包里,只需要你调用接口,就能使用复杂的功能。 下面举几个简单好玩的脚本例子,初学者可以照着代码写写,能快速掌握python语法。1、使用PIL、Matplotlib、Numpy对模糊老照片进行修复 encodingutf8importnumpyasnpimportmatplotlib。pyplotaspltfromPILimportImageimportos。path读取图片imgpathE:test。jpgimgImage。open(imgpath)图像转化为numpy数组imgnp。asarray(img)flatimg。flatten()创建函数defgethistogram(image,bins):arraywithsizeofbins,settozeroshistogramnp。zeros(bins)loopthroughpixelsandsumupcountsofpixelsforpixelinimage:histogram〔pixel〕1returnourfinalresultreturnhistogramexecuteourhistogramfunctionhistgethistogram(flat,256)executethefncsnp。cumsum(hist)numeratordenomenatornj(cscs。min())255Ncs。max()cs。min()renormalizethecumsumcsnjNcastitbacktouint8sincewecantusefloatingpointvaluesinimagescscs。astype(uint8)getthevaluefromcumulativesumforeveryindexinflat,andsetthatasimgnewimgnewcs〔flat〕putarraybackintooriginalshapesinceweflatteneditimgnewnp。reshape(imgnew,img。shape)setupsidebysideimagedisplayfigplt。figure()fig。setfigheight(15)fig。setfigwidth(15)displaytherealimagefig。addsubplot(1,2,1)plt。imshow(img,cmapgray)plt。title(ImageBeforeContrastAdjustment)displaythenewimagefig。addsubplot(1,2,2)plt。imshow(imgnew,cmapgray)plt。title(ImageAfterContrastAdjustment)filenameos。path。basename(imgpath)plt。savefig(E:filename)plt。show()2、将文件批量压缩,使用zipfile库importosimportzipfilefromrandomimportrandrangedefzipdir(path,ziphandler):forroot,dirs,filesinos。walk(path):forfileinfiles:ziphandler。write(os。path。join(root,file))ifnamemain:tozipinput(Enterthenameofthefolderyouwanttozip(N。B。:Thefoldernameshouldnotcontainblankspaces))toziptozip。strip()zipfilenamefzip{randrange(0,10000)}。zipzipfilezipfile。ZipFile(zipfilename,w,zipfile。ZIPDEFLATED)zipdir(tozip,zipfile)zipfile。close()print(fFileSavedas{zipfilename})3、使用tkinter制作计算器GUI tkinter是python自带的GUI库,适合初学者练手创建小软件 importtkinterastkroottk。Tk()Mainboxwindowroot。title(StandardCalculator)Titleshownatthetitlebarroot。resizable(0,0)disablingtheresizeingofthewindowCreatinganentryfield:etk。Entry(root,width35,bgf0ffff,fgblack,borderwidth5,justifyright,fontCalibri15)e。grid(row0,column0,columnspan3,padx12,pady12)defbuttonClick(num):functionforclickingtempe。get()temporaryvaribaletostorethecurrentinputinthescreene。delete(0,tk。END)clearingthescreenfromindex0toENDe。insert(0,tempnum)insertingtheincomingnumberinputdefbuttonClear():functionforclearinge。delete(0,tk。END)代码过长,部分略4、PDF转换为Word文件 使用pdf2docx库,可以将PDF文件转为Word格式 frompdf2docximportConverterimportosimportsysTakePDFspathasinputpdfinput(Enterthepathtoyourfile:)assertos。path。exists(pdf),Filenotfoundat,str(pdf)fopen(pdf,r)Askforcustomnamefortheworddocdocnamechoiceinput(Doyouwanttogiveacustomnametoyourfile?(YN))if(docnamechoiceYordocnamechoicey):Userinputdocnameinput(Enterthecustomname:)。docxelse:UsethesamenameaspdfGetthefilenamefromthepathprovidedbytheuserpdfnameos。path。basename(pdf)Getthenamewithouttheextension。pdfdocnameos。path。splitext(pdfname)〔0〕。docxConvertPDFtoWordcvConverter(pdf)Pathtothedirectorypathos。path。dirname(pdf)cv。convert(os。path。join(path,,docname),start0,endNone)print(Worddoccreated!)cv。close()5、Python自动发送邮件 使用smtplib和email库可以实现脚本发送邮件 importsmtplibimportemail负责构造文本fromemail。mime。textimportMIMEText负责构造图片fromemail。mime。imageimportMIMEImage负责将多个对象集合起来fromemail。mime。multipartimportMIMEMultipartfromemail。headerimportHeaderSMTP服务器,这里使用163邮箱mailhostsmtp。163。com发件人邮箱mailsender163。com邮箱授权码,注意这里不是邮箱密码,如何获取邮箱授权码,请看本文最后教程maillicense收件人邮箱,可以为多个收件人mailreceivers〔qq。com,outlook。com〕mmMIMEMultipart(related)邮件主题subjectcontentPython邮件测试设置发送者,注意严格遵守格式,里面邮箱为发件人邮箱mm〔From〕sendername163。com设置接受者,注意严格遵守格式,里面邮箱为接受者邮箱mm〔To〕receiver1nameqq。com,receiver2nameoutlook。com设置邮件主题mm〔Subject〕Header(subjectcontent,utf8)邮件正文内容bodycontent你好,这是一个测试邮件!构造文本,参数1:正文内容,参数2:文本格式,参数3:编码方式messagetextMIMEText(bodycontent,plain,utf8)向MIMEMultipart对象中添加文本对象mm。attach(messagetext)二进制读取图片imagedataopen(a。jpg,rb)设置读取获取的二进制数据messageimageMIMEImage(imagedata。read())关闭刚才打开的文件imagedata。close()添加图片文件到邮件信息当中去mm。attach(messageimage)构造附件attaMIMEText(open(sample。xlsx,rb)。read(),base64,utf8)设置附件信息atta〔ContentDisposition〕filenamesample。xlsx添加附件到邮件信息当中去mm。attach(atta)创建SMTP对象stpsmtplib。SMTP()设置发件人邮箱的域名和端口,端口地址为25stp。connect(mailhost,25)setdebuglevel(1)可以打印出和SMTP服务器交互的所有信息stp。setdebuglevel(1)登录邮箱,传递参数1:邮箱地址,参数2:邮箱授权码stp。login(mailsender,maillicense)发送邮件,传递参数1:发件人邮箱地址,参数2:收件人邮箱地址,参数3:把邮件内容格式改为strstp。sendmail(mailsender,mailreceivers,mm。asstring())print(邮件发送成功)关闭SMTP对象stp。quit()小结 Python还有很多好玩的小脚本,你可以根据自己的场景来编写,也可以使用现成的第三方库。