您每天可能会执行很多重复性的工作,例如阅读pdf、播放音乐、查看天气、打开书签、清理文件夹等,使用自动化脚本,您不需要一次又一次地手动完成这些工作,非常方便。在某种程度上,Python是自动化的代名词。今天分享6个非常有用的Python自动化脚本。1.PDF转音频文件该脚本可以将pdf文件转成音频文件。原理也很简单。首先使用PyPDF提取pdf中的文字,然后使用Pyttsx3将文字转为语音。对于文字转语音,还可以阅读这篇文章FastAPI:快速开发文字转语音接口。代码如下: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,'故事。mp3')##SavingTextInaaudiofile'story.mp3'speaker.runAndWait()speaker.stop()2.播放列表中的随机音乐此脚本将从歌曲文件夹中随机选择一首歌曲进行播放。需要注意的是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]))3.没有书签了。每天睡觉前都会在网上搜索一些好的内容,第二天再看。大多数时候,我会为遇到的网站或文章添加书签,但我的书签每天都在增长,现在我的浏览器中有超过100个书签。所以,在python的帮助下,我想出了另一种方法来解决这个问题。现在,我将这些站点的链接复制并粘贴到一个文本文件中,每天早上我运行脚本以在我的浏览器中再次打开所有这些站点。importwebbrowserwithopen('./websites.txt')asreader:forlinkinreader:webbrowser.open(link.strip())代码使用了webbrowser,这是Python中的一个库,可以在默认浏览器中自动打开网址。4.智能天气信息国家气象局网站提供获取天气预报的API,直接返回json格式的天气数据。所以只需要从json中取出相应的字段即可。以下是指定市(县、区)的天气网址。如果直接打开网址,会返回对应城市的天气数据。例如:http://www.weather.com.cn/data/cityinfo/101021200.html上海市徐汇区对应的天气网站。具体代码如下:importrequestsimportjsonimportloggingaslogdefget_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=请求。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)结果如下:5.长网址有时会变短,那些大网址变得非常烦人并且难以阅读和分享,这个页脚可以将长网址变成短网址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()这个脚本很有用的,比如内容平台屏蔽了公众号文章,那你可以把公众号文章的链接改成短链接,然后插入,就可以绕过:6.清理下载文件夹世界之最混乱最常见的事情之一就是开发者的下载文件夹,里面存放着很多乱七八糟的文件。此脚本将根据大小限制清理您的下载文件夹,并清理较旧的文件:dir_list,key=lambdax:os.path.getmtime(os.path.join(file_path,x)))returndir_listdefget_size(file_path):"""[summary]Args:file_path([type]):[directory]返回:[type]:返回目录大小,MB"""totalsize=0forfilenameinos.listdir(file_path):totalsize=totalsize+os.path.getsize(os.path.join(file_path,filenamee))#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])defdetectFileSize():#检测线程,每5秒检测一次whileTrue:print('======detect=============')detect_file_size("/Users/aaron/Downloads/",100,30)time.sleep(5)if__name__=="__main__":#创建检测线程detect_thread=threading.Thread(target=detectFileSize)detect_thread.start()可以通过以下二维码关注和转载本文,请联系7号蟒蛇公众号。
