当前位置: 首页 > 后端技术 > Python

Python脚本梳理

时间:2023-03-25 22:19:56 Python

1.使用PIL、Matplotlib、Numpy修复模糊老照片#encoding=utf-8importnumpyasnpiimportmatplotlib.pyplotaspltfromPILimportImageimportos.path#读取图片img_path="E:\\test.jpg"img=Image.open(img_path)#图像被转换为??numpy数组img=np.asarray(img)flat=img.flatten()#创建函数defget_histogram(image,bins):#具有bin大小的数组,设置为零histogram=np.zeros(bins)#遍历像素并对图像中像素的像素计数求和:histogram[pixel]+=1#返回我们的最终结果returnhistogram#执行我们的直方图functionhist=get_histogram(flat,256)#执行fncs=np.cumsum(hist)#numerator&denomenatornj=(cs-cs.min())*255N=cs.max()-cs.min()#re-normalizethecumsumcs=nj/N#castitback到uint8,因为我们不能在images中使用浮点值scs=cs.astype('uint8')#从flat中每个索引的累积和中获取值,并将其设置为img_newimg_new=cs[flat]#putarray背k变成原始形状,因为我们展平了itimg_new=np.reshape(img_new,img.shape)#setupside-by-sideimagedisplayfig=plt.figure()fig.set_figheight(15)fig.set_figwidth(15)#displaytherealimagefig.add_subplot(1,2,1)plt.imshow(img,cmap='gray')plt.title("Image'Before'ContrastAdjustment")#显示新imagefig.add_subplot(1,2,2)plt.imshow(img_new,cmap='gray')plt.title("Image'After'ContrastAdjustment")filename=os.path.basename(img_path)#plt.savefig("E:\\"+filename)plt.show()2、将文件批量压缩,使用zipfile库importosimportzipfilefromrandomimportrandrangedefzip_dir(path,zip_handler):forroot,dirs,filesinos.walk(path):forfileinfiles:zip_handler.write(os.path.join(root,file))if__name__=='__main__':to_zip=input("""输入要压缩的文件夹的名称(注意:文件夹名称不能包含空格)>""")to_zip=到_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、PDF转为Word文件使用pdf2docx库,可以将PDF文件转为Word格式frompdf2docximportConverterimportosimportsys#将PDF的路径作为输入pdf=input("Enterthepathtoyourfile:")assertos.path.exists(pdf),"Filenotfoundat,"+str(pdf)f=open(pdf,'r+')#Askforcustomnamefortheworddocdoc_name_choice=input("Doyouwanttogiveacustomnametoyourfile?(Y/N)")if(doc_name_choice=='Y'ordoc_name_choice=='y'):#用户输入doc_name=input("Enterthecustomname:")+".docx"else:#使用与pdf相同的名称#从用户提供的路径中获取文件名pdf_name=os.path.basename(pdf)#获取不带扩展名的名称。pdf文档ame=os.path.splitext(pdf_name)[0]+".docx"#ConvertPDFtoWordcv=Converter(pdf)#Pathtothedirectorypath=os.path.dirname(pdf)cv.convert(os.path.join(path,"",doc_name),start=0,end=None)print("Worddoccreated!")cv.close()4.Python自动发送邮件使用smtplib和email库实现脚本发送邮件importsmtplibimportemail#负责构造文本fromemail.mime.textimportMIMEText#负责构造图片fromemail.mime.imageimportMIMEImage#负责组合多个对象fromemail.mime.multipartimportMIMEMultipartfromemail.headerimportHeader#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")#添加文本对象mm到MIMEMultipart对象。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')#设置附件informationatta["Content-Disposition"]='attachment;filename="sample.xlsx"'#添加附件到邮件消息mm.attach(atta)#创建一个SMTP对象stp=smtplib.SMTP()#设置发件人邮箱的域名和端口,端口地址为25stp.connect(mail_host,25)#set_debuglevel(1)可以打印出所有与SMTP服务器交互的信息stp.set_debuglevel(1)#登录邮箱和过去参数1:邮箱地址,参数2:邮件授权码stp.login(mail_sender,mail_license)#发送邮件,传递参数1:发件人邮箱,参数2:收件人邮箱,参数3:将邮件内容格式改为strstp.sendmail(mail_sender,mail_receivers,mm.as_string())print("Mailsentsuccessfully")#关闭SMTP对象stp.quit()5.解析和提取HTML这个自动化脚本会帮你从网页URL中提取HTML,然后还为您提供可用于解析HTML数据的函数#解析和提取HTML#pipinstallgazpachoimportgazpacho#从URL中提取HTMLurl='https://www.example.com/'html=gazpacho.get(url)print(html)#使用Headersheaders={'User-Agent':'Mozilla/5.0'}html=gazpacho.get(url,headers=headers)print(html)#解析HTMLparse=gazpacho.Soup(html)#查找单个标签tag1=parse.find('h1')tag2=parse.find('span')#查找多个标签tags1=parse.find_all('p')tags2=parse.find_all('a')#通过classtag查找标签=parse.find('.class')#通过查找标签attributetag=parse.find("div",attrs={"class":"test"})#从标签中提取文本text=parse.find('h1').texttext=parse.find_all('p')[0].text6,QRcodescanner有很多QR码图片或者只是想扫描QR码图片,那么这个自动化脚本可以帮到你。此脚本使用Qrtools模块,使您能够以编程方式扫描QR图像。#QrcodeScanner#pipinstallqrtoolsfromqrtoolsimportQrdefScan_Qr(qr_img):qr=Qr()qr.decode(qr_img)print(qr.data)returnqr.dataprint("你的二维码是:",Scan_Qr("qr.png"))7.Screenshot#GrabScreenshot#pipinstallpyautogui#pipinstallPillowfrompyautoguiimportscreenshotimporttimefromPILimportImageGrab#GrabScreenshotofScreendefgrab_screenshot():shot=screenshot()shot.save('my_screenshot.png')复制代码#抓取特定区域的屏幕截图efgrab_screenshot_area():area=(0,0,500,500)shot=ImageGrab.grab(area)shot.save('my_screenshot_area.png')#使用Delaydef抓取屏幕截图grab_screenshot_delay():time.sleep(5)shot=screenshot()shot.save('my_screenshot_delay.png')8.创建有声读物将您的PDF书籍转换为有声读物,然后这是您的自动化脚本,它使用GTTS模块将您的PDF文本转换为音频。#创建有声读物#pipinstallgTTS#pipinstallPyPDF2fromPyPDF2importPdfFileReaderasreaderfromgttsimportgTTSdefcreate_audio(pdf_file):read_Pdf=reader(open(pdf_file,'rb'))forpageinrange(read_Pdf.numPages):text=read_Pdf.getPage(page).extractText()tts=gTTS(text,lang='en')tts.save('page'+str(page)+'.mp3')create_audio('book.pdf')9.视频Watermark使用这个使用Moviepy的自动化脚本为您的视频添加水印,这是一个方便的视频编辑模块。在下面的脚本中,您可以看到如何添加水印并自由使用。#使用Python的视频水印#pipinstallmoviepyfrommoviepy.editorimport*clip=VideoFileClip("myvideo.mp4",audio=True)width,height=clip.sizetext=TextClip("WaterMark",font='Arial',color='white',fontsize=28)set_color=text.on_color(size=(clip.w+text.w,text.h-10),color=(0,0,0),pos=(6,'center'),col_opacity=0.6)set_textPos=set_color.set_pos(lambdapos:(max(width/30,int(width-0.5*width*pos)),max(5*height/6,int(100*pos))))Output=CompositeVideoClip([clip,set_textPos])Output.duration=clip.durationOutput.write_videofile("output.mp4",fps=30,codec='libx264')后续有更好的补充》