自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

六個實用的 Python 自動化腳本,你學會了嗎?

開發(fā) 后端 自動化
每天你都可能會執(zhí)行許多重復的任務,例如閱讀 pdf、播放音樂、查看天氣、打開書簽、清理文件夾等等,使用自動化腳本,就無需手動一次又一次地完成這些任務,非常方便。而在某種程度上,Python 就是自動化的代名詞。

[[437489]]

每天你都可能會執(zhí)行許多重復的任務,例如閱讀 pdf、播放音樂、查看天氣、打開書簽、清理文件夾等等,使用自動化腳本,就無需手動一次又一次地完成這些任務,非常方便。而在某種程度上,Python 就是自動化的代名詞。今天分享 6 個非常有用的 Python 自動化腳本。

1、將 PDF 轉(zhuǎn)換為音頻文件

腳本可以將 pdf 轉(zhuǎn)換為音頻文件,原理也很簡單,首先用 PyPDF 提取 pdf 中的文本,然后用 Pyttsx3 將文本轉(zhuǎn)語音。關(guān)于文本轉(zhuǎn)語音,你還可以看這篇文章FastAPI:快速開發(fā)一個文本轉(zhuǎn)語音的接口。

代碼如下:

  1. import pyttsx3,PyPDF2 
  2. pdfreader = PyPDF2.PdfFileReader(open('story.pdf','rb')) 
  3. speaker = pyttsx3.init() 
  4. for page_num in range(pdfreader.numPages):    
  5.     text = pdfreader.getPage(page_num).extractText()  ## extracting text from the PDF 
  6.     cleaned_text = text.strip().replace('\n',' ')  ## Removes unnecessary spaces and break lines 
  7.     print(cleaned_text)                ## Print the text from PDF 
  8.     #speaker.say(cleaned_text)        ## Let The Speaker Speak The Text 
  9.     speaker.save_to_file(cleaned_text,'story.mp3')  ## Saving Text In a audio file 'story.mp3' 
  10.     speaker.runAndWait() 
  11. speaker.stop() 

2、從列表中播放隨機音樂

這個腳本會從歌曲文件夾中隨機選擇一首歌進行播放,需要注意的是 os.startfile 僅支持 Windows 系統(tǒng)。

  1. import random, os 
  2. music_dir = 'G:\\new english songs' 
  3. songs = os.listdir(music_dir) 
  4. song = random.randint(0,len(songs)) 
  5. print(songs[song])  ## Prints The Song Name 
  6. os.startfile(os.path.join(music_dir, songs[0]))  

3、不再有書簽了

每天睡覺前,我都會在網(wǎng)上搜索一些好內(nèi)容,第二天可以閱讀。大多數(shù)時候,我把遇到的網(wǎng)站或文章添加為書簽,但我的書簽每天都在增加,以至于現(xiàn)在我的瀏覽器周圍有100多個書簽。因此,在python的幫助下,我想出了另一種方法來解決這個問題?,F(xiàn)在,我把這些網(wǎng)站的鏈接復制粘貼到文本文件中,每天早上我都會運行腳本,在我的瀏覽器中再次打開所有這些網(wǎng)站。

  1. import webbrowser 
  2. with open('./websites.txt'as reader: 
  3.     for link in reader: 
  4.         webbrowser.open(link.strip()) 

代碼用到了 webbrowser,是 Python 中的一個庫,可以自動在默認瀏覽器中打開 URL。

4、智能天氣信息

國家氣象局網(wǎng)站提供獲取天氣預報的 API,直接返回 json 格式的天氣數(shù)據(jù)。所以只需要從 json 里取出對應的字段就可以了。

下面是指定城市(縣、區(qū))天氣的網(wǎng)址,直接打開網(wǎng)址,就會返回對應城市的天氣數(shù)據(jù)。比如:

  1. http://www.weather.com.cn/data/cityinfo/101021200.html上海徐匯區(qū)對應的天氣網(wǎng)址。 

具體代碼如下:

  1. import requests 
  2. import json 
  3. import logging as log 
  4.  
  5. def get_weather_wind(url): 
  6.     r = requests.get(url) 
  7.     if r.status_code != 200: 
  8.         log.error("Can't get weather data!"
  9.     info = json.loads(r.content.decode()) 
  10.  
  11.     # get wind data 
  12.     data = info['weatherinfo'
  13.     WD = data['WD'
  14.     WS = data['WS'
  15.     return "{}({})".format(WD, WS) 
  16.  
  17.  
  18. def get_weather_city(url): 
  19.     # open url and get return data 
  20.     r = requests.get(url) 
  21.     if r.status_code != 200: 
  22.         log.error("Can't get weather data!"
  23.  
  24.     # convert string to json 
  25.     info = json.loads(r.content.decode()) 
  26.  
  27.     # get useful data 
  28.     data = info['weatherinfo'
  29.     city = data['city'
  30.     temp1 = data['temp1'
  31.     temp2 = data['temp2'
  32.     weather = data['weather'
  33.     return "{} {} {}~{}".format(city, weather, temp1, temp2) 
  34.  
  35.  
  36. if __name__ == '__main__'
  37.     msg = """**天氣提醒**:   
  38.  
  39. {} {}   
  40. {} {}   
  41.  
  42. 來源: 國家氣象局 
  43. """.format( 
  44.     get_weather_city('http://www.weather.com.cn/data/cityinfo/101021200.html'), 
  45.     get_weather_wind('http://www.weather.com.cn/data/sk/101021200.html'), 
  46.     get_weather_city('http://www.weather.com.cn/data/cityinfo/101020900.html'), 
  47.     get_weather_wind('http://www.weather.com.cn/data/sk/101020900.html'
  48.     print(msg) 

運行結(jié)果如下所示:

5、長網(wǎng)址變短網(wǎng)址

有時,那些大URL變得非常惱火,很難閱讀和共享,此腳可以將長網(wǎng)址變?yōu)槎叹W(wǎng)址。

  1. import contextlib 
  2. from urllib.parse import urlencode 
  3. from urllib.request import urlopen 
  4. import sys 
  5.  
  6. def make_tiny(url): 
  7.  request_url = ('http://tinyurl.com/api-create.php?' +  
  8.  urlencode({'url':url})) 
  9.  with contextlib.closing(urlopen(request_url)) as response: 
  10.   return response.read().decode('utf-8'
  11.  
  12. def main(): 
  13.  for tinyurl in map(make_tiny, sys.argv[1:]): 
  14.   print(tinyurl) 
  15.  
  16. if __name__ == '__main__'
  17.  main() 

這個腳本非常實用,比如說有不是內(nèi)容平臺是屏蔽公眾號文章的,那么就可以把公眾號文章的鏈接變?yōu)槎替溄?,然后插入其中,就可以實現(xiàn)繞過:

6、清理下載文件夾

世界上最混亂的事情之一是開發(fā)人員的下載文件夾,里面存放了很多雜亂無章的文件,此腳本將根據(jù)大小限制來清理您的下載文件夾,有限清理比較舊的文件:

  1. import os 
  2. import threading 
  3. import time 
  4.   
  5.   
  6. def get_file_list(file_path): 
  7. #文件按最后修改時間排序 
  8.     dir_list = os.listdir(file_path) 
  9.     if not dir_list: 
  10.         return 
  11.     else
  12.         dir_list = sorted(dir_list, key=lambda x: os.path.getmtime(os.path.join(file_path, x))) 
  13.     return dir_list 
  14.   
  15. def get_size(file_path): 
  16.     """[summary] 
  17.     Args: 
  18.         file_path ([type]): [目錄] 
  19.  
  20.     Returns
  21.         [type]: 返回目錄大小,MB 
  22.     ""
  23.     totalsize=0 
  24.     for filename in os.listdir(file_path): 
  25.         totalsize=totalsize+os.path.getsize(os.path.join(file_path, filename)) 
  26.     #print(totalsize / 1024 / 1024) 
  27.     return totalsize / 1024 / 1024 
  28.   
  29. def detect_file_size(file_path, size_Max, size_Del): 
  30.     """[summary] 
  31.     Args: 
  32.         file_path ([type]): [文件目錄] 
  33.         size_Max ([type]): [文件夾最大大小] 
  34.         size_Del ([type]): [超過size_Max時要刪除的大小] 
  35.     ""
  36.     print(get_size(file_path)) 
  37.     if get_size(file_path) > size_Max: 
  38.         fileList = get_file_list(file_path) 
  39.         for i in range(len(fileList)): 
  40.             if get_size(file_path) > (size_Max - size_Del): 
  41.                 print ("del :%d %s" % (i + 1, fileList[i])) 
  42.                 #os.remove(file_path + fileList[i]) 
  43.      
  44.   
  45. def detectFileSize(): 
  46.  #檢測線程,每個5秒檢測一次 
  47.     while True
  48.         print('======detect============'
  49.         detect_file_size("/Users/aaron/Downloads/", 100, 30) 
  50.         time.sleep(5) 
  51.    
  52. if __name__ == "__main__"
  53.     #創(chuàng)建檢測線程 
  54.     detect_thread = threading.Thread(target = detectFileSize) 
  55.     detect_thread.start() 

本文轉(zhuǎn)載自微信公眾號「Python七號」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系Python七號公眾號。

 

責任編輯:武曉燕 來源: Python七號
相關(guān)推薦

2025-04-02 08:20:00

Python自動化文件管理腳本模板

2022-04-28 08:24:16

阿里云idaaspython

2025-03-20 08:30:00

Python編程文件管理

2023-08-22 10:25:19

CSS動畫網(wǎng)頁

2024-05-29 07:47:30

SpringJava@Resource

2024-11-13 13:14:38

2021-12-14 14:33:44

人工智能AI深度學習

2023-05-04 10:30:39

自動駕駛自動化

2022-07-08 09:27:48

CSSIFC模型

2024-02-02 11:03:11

React數(shù)據(jù)Ref

2023-09-07 07:13:51

2023-01-10 08:43:15

定義DDD架構(gòu)

2024-02-04 00:00:00

Effect數(shù)據(jù)組件

2023-07-26 13:11:21

ChatGPT平臺工具

2024-01-19 08:25:38

死鎖Java通信

2024-01-02 12:05:26

Java并發(fā)編程

2023-08-01 12:51:18

WebGPT機器學習模型

2023-06-06 07:50:07

權(quán)限管理hdfsacl

2021-07-01 19:22:33

腳本Shell參數(shù)

2022-12-08 10:49:43

點贊
收藏

51CTO技術(shù)棧公眾號