6個(gè)實(shí)用的Python自動(dòng)化腳本詳解
每天你都可能會(huì)執(zhí)行許多重復(fù)的任務(wù),例如閱讀 pdf、播放音樂(lè)、查看天氣、打開(kāi)書(shū)簽、清理文件夾等等,使用自動(dòng)化腳本,就無(wú)需手動(dòng)一次又一次地完成這些任務(wù),非常方便。而在某種程度上,Python 就是自動(dòng)化的代名詞。今天分享 6 個(gè)非常有用的 Python 自動(dòng)化腳本。
1、將 PDF 轉(zhuǎn)換為音頻文件
腳本可以將 pdf 轉(zhuǎn)換為音頻文件,原理也很簡(jiǎn)單,首先用 PyPDF 提取 pdf 中的文本,然后用 Pyttsx3 將文本轉(zhuǎn)語(yǔ)音。關(guān)于文本轉(zhuǎn)語(yǔ)音,你還可以看這篇文章FastAPI:快速開(kāi)發(fā)一個(gè)文本轉(zhuǎn)語(yǔ)音的接口。
代碼如下:
import pyttsx3,PyPDF2 pdfreader = PyPDF2.PdfFileReader(open('story.pdf','rb')) speaker = pyttsx3.init() for page_num in range(pdfreader.numPages): text = pdfreader.getPage(page_num).extractText() ## extracting text from the PDF cleaned_text = text.strip().replace('\n',' ') ## Removes unnecessary spaces and break lines print(cleaned_text) ## Print the text from PDF #speaker.say(cleaned_text) ## Let The Speaker Speak The Text speaker.save_to_file(cleaned_text,'story.mp3') ## Saving Text In a audio file 'story.mp3' speaker.runAndWait() speaker.stop()
2、從列表中播放隨機(jī)音樂(lè)
這個(gè)腳本會(huì)從歌曲文件夾中隨機(jī)選擇一首歌進(jìn)行播放,需要注意的是 os.startfile 僅支持 Windows 系統(tǒng)。
import random, os music_dir = 'G:\\new english songs' songs = os.listdir(music_dir) song = random.randint(0,len(songs)) print(songs[song]) ## Prints The Song Name os.startfile(os.path.join(music_dir, songs[0]))
3、不再有書(shū)簽了
每天睡覺(jué)前,我都會(huì)在網(wǎng)上搜索一些好內(nèi)容,第二天可以閱讀。大多數(shù)時(shí)候,我把遇到的網(wǎng)站或文章添加為書(shū)簽,但我的書(shū)簽每天都在增加,以至于現(xiàn)在我的瀏覽器周?chē)?00多個(gè)書(shū)簽。因此,在python的幫助下,我想出了另一種方法來(lái)解決這個(gè)問(wèn)題?,F(xiàn)在,我把這些網(wǎng)站的鏈接復(fù)制粘貼到文本文件中,每天早上我都會(huì)運(yùn)行腳本,在我的瀏覽器中再次打開(kāi)所有這些網(wǎng)站。
import webbrowser with open('./websites.txt') as reader: for link in reader: webbrowser.open(link.strip())
代碼用到了 webbrowser,是 Python 中的一個(gè)庫(kù),可以自動(dòng)在默認(rèn)瀏覽器中打開(kāi) URL。
4、智能天氣信息
國(guó)家氣象局網(wǎng)站提供獲取天氣預(yù)報(bào)的 API,直接返回 json 格式的天氣數(shù)據(jù)。所以只需要從 json 里取出對(duì)應(yīng)的字段就可以了。
下面是指定城市(縣、區(qū))天氣的網(wǎng)址,直接打開(kāi)網(wǎng)址,就會(huì)返回對(duì)應(yīng)城市的天氣數(shù)據(jù)。比如:
http://www.weather.com.cn/data/cityinfo/101021200.html上海徐匯區(qū)對(duì)應(yīng)的天氣網(wǎng)址。
具體代碼如下:
import requests import json import logging as log def get_weather_wind(url): r = requests.get(url) if r.status_code != 200: log.error("Can't get weather data!") info = json.loads(r.content.decode()) # get wind data data = info['weatherinfo'] WD = data['WD'] WS = data['WS'] return "{}({})".format(WD, WS) def get_weather_city(url): # open url and get return data r = requests.get(url) if r.status_code != 200: log.error("Can't get weather data!") # convert string to json info = json.loads(r.content.decode()) # get useful data data = info['weatherinfo'] city = data['city'] temp1 = data['temp1'] temp2 = data['temp2'] weather = data['weather'] return "{} {} {}~{}".format(city, weather, temp1, temp2) if __name__ == '__main__': msg = """**天氣提醒**: {} {} {} {} 來(lái)源: 國(guó)家氣象局 """.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)
運(yùn)行結(jié)果如下所示:
5、長(zhǎng)網(wǎng)址變短網(wǎng)址
有時(shí),那些大URL變得非常惱火,很難閱讀和共享,此腳可以將長(zhǎng)網(wǎng)址變?yōu)槎叹W(wǎng)址。
import contextlib from urllib.parse import urlencode from urllib.request import urlopen import sys def make_tiny(url): request_url = ('http://tinyurl.com/api-create.php?' + urlencode({'url':url})) with contextlib.closing(urlopen(request_url)) as response: return response.read().decode('utf-8') def main(): for tinyurl in map(make_tiny, sys.argv[1:]): print(tinyurl) if __name__ == '__main__': main()
這個(gè)腳本非常實(shí)用,比如說(shuō)有不是內(nèi)容平臺(tái)是屏蔽公眾號(hào)文章的,那么就可以把公眾號(hào)文章的鏈接變?yōu)槎替溄?,然后插入其中,就可以?shí)現(xiàn)繞過(guò):
6、清理下載文件夾
世界上最混亂的事情之一是開(kāi)發(fā)人員的下載文件夾,里面存放了很多雜亂無(wú)章的文件,此腳本將根據(jù)大小限制來(lái)清理您的下載文件夾,有限清理比較舊的文件:
import os import threading import time def get_file_list(file_path): #文件按最后修改時(shí)間排序 dir_list = os.listdir(file_path) if not dir_list: return else: dir_list = sorted(dir_list, key=lambda x: os.path.getmtime(os.path.join(file_path, x))) return dir_list def get_size(file_path): """[summary] Args: file_path ([type]): [目錄](méi) Returns: [type]: 返回目錄大小,MB """ totalsize=0 for filename in os.listdir(file_path): totalsize=totalsize+os.path.getsize(os.path.join(file_path, filename)) #print(totalsize / 1024 / 1024) return totalsize / 1024 / 1024 def detect_file_size(file_path, size_Max, size_Del): """[summary] Args: file_path ([type]): [文件目錄](méi) size_Max ([type]): [文件夾最大大小] size_Del ([type]): [超過(guò)size_Max時(shí)要?jiǎng)h除的大小] """ print(get_size(file_path)) if get_size(file_path) > size_Max: fileList = get_file_list(file_path) for i in range(len(fileList)): if get_size(file_path) > (size_Max - size_Del): print ("del :%d %s" % (i + 1, fileList[i])) #os.remove(file_path + fileList[i]) def detectFileSize(): #檢測(cè)線程,每個(gè)5秒檢測(cè)一次 while True: print('======detect============') detect_file_size("/Users/aaron/Downloads/", 100, 30) time.sleep(5) if __name__ == "__main__": #創(chuàng)建檢測(cè)線程 detect_thread = threading.Thread(target = detectFileSize) detect_thread.start()
到此這篇關(guān)于6個(gè)實(shí)用的Python自動(dòng)化腳本詳解的文章就介紹到這了,更多相關(guān)Python自動(dòng)化腳本內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python-flask調(diào)用接口返回中文數(shù)據(jù)問(wèn)題
這篇文章主要介紹了Python-flask調(diào)用接口返回中文數(shù)據(jù)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03Kears 使用:通過(guò)回調(diào)函數(shù)保存最佳準(zhǔn)確率下的模型操作
這篇文章主要介紹了Kears 使用:通過(guò)回調(diào)函數(shù)保存最佳準(zhǔn)確率下的模型操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06Python super( )函數(shù)用法總結(jié)
今天給大家?guī)?lái)的知識(shí)是關(guān)于Python的相關(guān)知識(shí),文章圍繞著super( )函數(shù)展開(kāi),文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06解決運(yùn)行出現(xiàn)''dict'' object has no attribute ''has_key''問(wèn)題
這篇文章主要介紹了快速解決出現(xiàn)class object has no attribute ' functiong' or 'var'問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07在tensorflow實(shí)現(xiàn)直接讀取網(wǎng)絡(luò)的參數(shù)(weight and bias)的值
這篇文章主要介紹了在tensorflow實(shí)現(xiàn)直接讀取網(wǎng)絡(luò)的參數(shù)(weight and bias)的值,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06python模擬實(shí)現(xiàn)斗地主發(fā)牌
這篇文章主要為大家詳細(xì)介紹了python代碼模擬實(shí)現(xiàn)斗地主發(fā)牌,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-01-01Python將多個(gè)圖像合并輸出的實(shí)現(xiàn)方法
這篇文章主要介紹了Python將多個(gè)圖像合并輸出的實(shí)現(xiàn)方法,本文介紹了兩種將多個(gè)圖像合并為一個(gè)輸出的方法:使用PIL庫(kù)或使用OpenCV和NumPy,這些庫(kù)都可以使用Python中的簡(jiǎn)單語(yǔ)法和少量的代碼來(lái)完成此任務(wù),需要的朋友可以參考下2023-06-06