您的位置:首页 >聚焦 >

环球今日讯!值得推荐!分享8个超好用的 Python 自动化脚本!

2022-06-25 09:38:13    来源:程序员客栈
↓推荐关注↓

每天你都可能会执行许多重复的任务,例如阅读新闻、发邮件、查看天气、清理文件夹等等,使用自动化脚本,就无需手动一次又一次地完成这些任务,非常方便。而在某种程度上,Python 就是自动化的代名词。

今天分享 8 个非常有用的 Python 自动化脚本。喜欢记得收藏、关注、点赞。


(资料图)

1、自动化阅读网页新闻

这个脚本能够实现从网页中抓取文本,然后自动化语音朗读,当你想听新闻的时候,这是个不错的选择。

代码分为两大部分,第一通过爬虫抓取网页文本呢,第二通过阅读工具来朗读文本。

需要的第三方库:

Beautiful Soup - 经典的HTML/XML文本解析器,用来提取爬下来的网页信息

requests - 好用到逆天的HTTP工具,用来向网页发送请求获取数据

Pyttsx3 - 将文本转换为语音,并控制速率、频率和语音

importpyttsx3importrequestsfrombs4importBeautifulSoupengine=pyttsx3.init("sapi5")voices=engine.getProperty("voices")newVoiceRate=130##ReduceTheSpeechRateengine.setProperty("rate",newVoiceRate)engine.setProperty("voice",voices[1].id)defspeak(audio):engine.say(audio)engine.runAndWait()text=str(input("Pastearticle\n"))res=requests.get(text)soup=BeautifulSoup(res.text,"html.parser")articles=[]foriinrange(len(soup.select(".p"))):article=soup.select(".p")[i].getText().strip()articles.append(article)text="".join(articles)speak(text)#engine.save_to_file(text,"test.mp3")##Ifyouwanttosavethespeechasaaudiofileengine.runAndWait()

2、自动化数据探索

数据探索是数据科学项目的第一步,你需要了解数据的基本信息才能进一步分析更深的价值。

一般我们会用pandas、matplotlib等工具来探索数据,但需要自己编写大量代码,如果想提高效率,Dtale是个不错的选择。

Dtale特点是用一行代码生成自动化分析报告,它结合了Flask后端和React前端,为我们提供了一种查看和分析Pandas数据结构的简便方法。

我们可以在Jupyter上实用Dtale。

需要的第三方库:

Dtale - 自动生成分析报告

###ImportingSeabornLibraryForSomeDatasetsimportseabornassns###PrintingInbuiltDatasetsofSeabornLibraryprint(sns.get_dataset_names())###LoadingTitanicDatasetdf=sns.load_dataset("titanic")###ImportingTheLibraryimportdtale####GeneratingQuickSummarydtale.show(df)

3、自动发送多封邮件

这个脚本可以帮助我们批量定时发送邮件,邮件内容、附件也可以自定义调整,非常的实用。

相比较邮件客户端,Python脚本的优点在于可以智能、批量、高定制化地部署邮件服务。

需要的第三方库:

Email - 用于管理电子邮件消息

Smtlib - 向SMTP服务器发送电子邮件,它定义了一个 SMTP 客户端会话对象,该对象可将邮件发送到互联网上任何带有 SMTP 或 ESMTP 监听程序的计算机

Pandas - 用于数据分析清洗的工具

importsmtplibfromemail.messageimportEmailMessageimportpandasaspddefsend_email(remail,rsubject,rcontent):email=EmailMessage()##CreatingaobjectforEmailMessageemail["from"]="ThePythoneerHere"##Personwhoissendingemail["to"]=remail##Whomwearesendingemail["subject"]=rsubject##Subjectofemailemail.set_content(rcontent)##contentofemailwithsmtplib.SMTP(host="smtp.gmail.com",port=587)assmtp:smtp.ehlo()##serverobjectsmtp.starttls()##usedtosenddatabetweenserverandclientsmtp.login("deltadelta371@gmail.com","delta@371")##loginidandpasswordofgmailsmtp.send_message(email)##Sendingemailprint("emailsendto",remail)##Printingsuccessmessageif__name__=="__main__":df=pd.read_excel("list.xlsx")length=len(df)+1forindex,itemindf.iterrows():email=item[0]subject=item[1]content=item[2]send_email(email,subject,content)

4、将 PDF 转换为音频文件

脚本可以将 pdf 转换为音频文件,原理也很简单,首先用 PyPDF 提取 pdf 中的文本,然后用 Pyttsx3 将文本转语音。

importpyttsx3,PyPDF2pdfreader=PyPDF2.PdfFileReader(open("story.pdf","rb"))speaker=pyttsx3.init()forpage_numinrange(pdfreader.numPages):text=pdfreader.getPage(page_num).extractText()##extractingtextfromthePDFcleaned_text=text.strip().replace("\n","")##Removesunnecessaryspacesandbreaklinesprint(cleaned_text)##PrintthetextfromPDF#speaker.say(cleaned_text)##LetTheSpeakerSpeakTheTextspeaker.save_to_file(cleaned_text,"story.mp3")##SavingTextInaaudiofile"story.mp3"speaker.runAndWait()speaker.stop()

5、从列表中播放随机音乐

这个脚本会从歌曲文件夹中随机选择一首歌进行播放,需要注意的是 os.startfile 仅支持 Windows 系统。

importrandom,osmusic_dir="G:\\newenglishsongs"songs=os.listdir(music_dir)song=random.randint(0,len(songs))print(songs[song])##PrintsTheSongNameos.startfile(os.path.join(music_dir,songs[0]))

6、智能天气信息

国家气象局网站提供获取天气预报的 API,直接返回 json 格式的天气数据。所以只需要从 json 里取出对应的字段就可以了。

下面是指定城市(县、区)天气的网址,直接打开网址,就会返回对应城市的天气数据。比如:

http://www.weather.com.cn/data/cityinfo/101021200.html 上海徐汇区对应的天气网址。

具体代码如下:

mportrequestsimportjsonimportloggingaslogdefget_weather_wind(url):r=requests.get(url)ifr.status_code!=200:log.error("Can"tgetweatherdata!")info=json.loads(r.content.decode())#getwinddatadata=info["weatherinfo"]WD=data["WD"]WS=data["WS"]return"{}({})".format(WD,WS)defget_weather_city(url):#openurlandgetreturndatar=requests.get(url)ifr.status_code!=200:log.error("Can"tgetweatherdata!")#convertstringtojsoninfo=json.loads(r.content.decode())#getusefuldatadata=info["weatherinfo"]city=data["city"]temp1=data["temp1"]temp2=data["temp2"]weather=data["weather"]return"{}{}{}~{}".format(city,weather,temp1,temp2)if__name__=="__main__":msg="""**天气提醒**:{}{}{}{}来源:国家气象局""".format(get_weather_city("http://www.weather.com.cn/data/cityinfo/101021200.html"),get_weather_wind("http://www.weather.com.cn/data/sk/101021200.html"),get_weather_city("http://www.weather.com.cn/data/cityinfo/101020900.html"),get_weather_wind("http://www.weather.com.cn/data/sk/101020900.html"))print(msg)

运行结果如下所示:

7、长网址变短网址

有时,那些大URL变得非常恼火,很难阅读和共享,此脚可以将长网址变为短网址。

importcontextlibfromurllib.parseimporturlencodefromurllib.requestimporturlopenimportsysdefmake_tiny(url):request_url=("http://tinyurl.com/api-create.php?"+urlencode({"url":url}))withcontextlib.closing(urlopen(request_url))asresponse:returnresponse.read().decode("utf-8")defmain():fortinyurlinmap(make_tiny,sys.argv[1:]):print(tinyurl)if__name__=="__main__":main()

这个脚本非常实用,比如说有内容平台是屏蔽公众号文章的,那么就可以把公众号文章的链接变为短链接,然后插入其中,就可以实现绕过

8、清理下载文件夹

世界上最混乱的事情之一是开发人员的下载文件夹,里面存放了很多杂乱无章的文件,此脚本将根据大小限制来清理您的下载文件夹,有限清理比较旧的文件:

importosimportthreadingimporttimedefget_file_list(file_path):#文件按最后修改时间排序dir_list=os.listdir(file_path)ifnotdir_list:returnelse:dir_list=sorted(dir_list,key=lambdax:os.path.getmtime(os.path.join(file_path,x)))returndir_listdefget_size(file_path):"""[summary]Args:file_path([type]):[目录]Returns:[type]:返回目录大小,MB"""totalsize=0forfilenameinos.listdir(file_path):totalsize=totalsize+os.path.getsize(os.path.join(file_path,filename))#print(totalsize/1024/1024)returntotalsize/1024/1024defdetect_file_size(file_path,size_Max,size_Del):"""[summary]Args:file_path([type]):[文件目录]size_Max([type]):[文件夹最大大小]size_Del([type]):[超过size_Max时要删除的大小]"""print(get_size(file_path))ifget_size(file_path)>size_Max:fileList=get_file_list(file_path)foriinrange(len(fileList)):ifget_size(file_path)>(size_Max-size_Del):print("del:%d%s"%(i+1,fileList[i]))#os.remove(file_path+fileList[i])

长按或扫描下方二维码,后台回复:加群,即可申请入群。一定要备注:来源+研究方向+学校/公司,否则不拉入群中,见谅!

(长按三秒,进入后台)

 

关键词: 国家气象局 分析报告 能够实现

相关阅读