網站首頁 編程語言 正文
每天你都可能會執行許多重復的任務,例如閱讀 pdf、播放音樂、查看天氣、打開書簽、清理文件夾等等,使用自動化腳本,就無需手動一次又一次地完成這些任務,非常方便。而在某種程度上,Python 就是自動化的代名詞。今天分享 6 個非常有用的 Python 自動化腳本。
1、將 PDF 轉換為音頻文件
腳本可以將 pdf 轉換為音頻文件,原理也很簡單,首先用 PyPDF 提取 pdf 中的文本,然后用 Pyttsx3 將文本轉語音。關于文本轉語音,你還可以看這篇文章FastAPI:快速開發一個文本轉語音的接口。
代碼如下:
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、從列表中播放隨機音樂
這個腳本會從歌曲文件夾中隨機選擇一首歌進行播放,需要注意的是 os.startfile 僅支持 Windows 系統。
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、不再有書簽了
每天睡覺前,我都會在網上搜索一些好內容,第二天可以閱讀。大多數時候,我把遇到的網站或文章添加為書簽,但我的書簽每天都在增加,以至于現在我的瀏覽器周圍有100多個書簽。因此,在python的幫助下,我想出了另一種方法來解決這個問題。現在,我把這些網站的鏈接復制粘貼到文本文件中,每天早上我都會運行腳本,在我的瀏覽器中再次打開所有這些網站。
import webbrowser with open('./websites.txt') as reader: for link in reader: webbrowser.open(link.strip())
代碼用到了 webbrowser,是 Python 中的一個庫,可以自動在默認瀏覽器中打開 URL。
4、智能天氣信息
國家氣象局網站提供獲取天氣預報的 API,直接返回 json 格式的天氣數據。所以只需要從 json 里取出對應的字段就可以了。
下面是指定城市(縣、區)天氣的網址,直接打開網址,就會返回對應城市的天氣數據。比如:
http://www.weather.com.cn/data/cityinfo/101021200.html上海徐匯區對應的天氣網址。?
具體代碼如下:
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 = """**天氣提醒**: {} {} {} {} 來源: 國家氣象局 """.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、長網址變短網址
有時,那些大URL變得非常惱火,很難閱讀和共享,此腳可以將長網址變為短網址。
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()
這個腳本非常實用,比如說有不是內容平臺是屏蔽公眾號文章的,那么就可以把公眾號文章的鏈接變為短鏈接,然后插入其中,就可以實現繞過:
6、清理下載文件夾
世界上最混亂的事情之一是開發人員的下載文件夾,里面存放了很多雜亂無章的文件,此腳本將根據大小限制來清理您的下載文件夾,有限清理比較舊的文件:
import os import threading import time def get_file_list(file_path): #文件按最后修改時間排序 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]): [目錄] 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]): [文件目錄] size_Max ([type]): [文件夾最大大小] size_Del ([type]): [超過size_Max時要刪除的大小] """ 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(): #檢測線程,每個5秒檢測一次 while True: 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()
原文鏈接:https://blog.csdn.net/Python4857/article/details/121631389
相關推薦
- 2022-04-01 k8s報錯:Error from server (NotFound): the server cou
- 2022-06-22 git工作區暫存區與版本庫基本理解及提交流程全解_其它綜合
- 2022-01-16 1.把字符串轉化為時間戳,再將時間戳轉化為Date對象 /** *@parame time = 2
- 2022-09-17 Python中re.findall()用法詳解_python
- 2022-11-13 kvm?透傳顯卡至win10虛擬機的方法_Kvm
- 2023-05-06 Go語言中Slice常見陷阱與避免方法詳解_Golang
- 2022-10-17 Nginx中root與alias區別講解_nginx
- 2022-10-26 C語言實現自行車管理系統_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支