六个实用的 Python 自动化脚本,你学会了吗?

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

[[437489]]

每天你都可能会执行许多重复的任务,例如阅读 pdf、播放音乐、查看天气、打开书签、清理文件夹等等,使用自动化脚本,就无需手动一次又一次地完成这些任务,非常方便。而在某种程度上,Python 就是自动化的代名词。今天分享 6 个非常有用的 Python 自动化脚本。

1、将 PDF 转换为音频文件

脚本可以将 pdf 转换为音频文件,原理也很简单,首先用 PyPDF 提取 pdf 中的文本,然后用 Pyttsx3 将文本转语音。关于文本转语音,你还可以看这篇文章FastAPI:快速开发一个文本转语音的接口。

代码如下:

  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 系统。

  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、不再有书签了

每天睡觉前,我都会在网上搜索一些好内容,第二天可以阅读。大多数时候,我把遇到的网站或文章添加为书签,但我的书签每天都在增加,以至于现在我的浏览器周围有100多个书签。因此,在python的帮助下,我想出了另一种方法来解决这个问题。现在,我把这些网站的链接复制粘贴到文本文件中,每天早上我都会运行脚本,在我的浏览器中再次打开所有这些网站。

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

代码用到了 webbrowser,是 Python 中的一个库,可以自动在默认浏览器中打开 URL。

4、智能天气信息

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

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

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

具体代码如下:

  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) 

运行结果如下所示:

5、长网址变短网址

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

  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() 

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

6、清理下载文件夹

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

  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.     #创建检测线程 
  54.     detect_thread = threading.Thread(target = detectFileSize) 
  55.     detect_thread.start() 

本文转载自微信公众号「Python七号」,可以通过以下二维码关注。转载本文请联系Python七号公众号。

 

责任编辑:武晓燕 来源: Python七号
相关推荐

2022-04-28 08:24:16

阿里云idaaspython

2023-08-22 10:25:19

CSS动画网页

2023-05-04 10:30:39

自动驾驶自动化

2024-02-02 11:03:11

React数据Ref

2021-12-14 14:33:44

人工智能AI深度学习

2023-09-07 07:13:51

2023-08-01 12:51:18

WebGPT机器学习模型

2024-01-02 12:05:26

Java并发编程

2024-02-26 17:42:50

SSL证书命令

2019-06-19 08:09:05

CSSJavaScript前端

2022-12-06 08:37:43

2024-02-21 19:02:05

Go模板化方式

2023-07-10 07:17:29

无效化空窗口

2023-01-31 08:02:18

2024-03-06 08:28:16

设计模式Java

2022-12-06 07:53:33

MySQL索引B+树

2022-06-16 07:50:35

数据结构链表

2023-05-05 06:54:07

MySQL数据查询

2023-10-06 14:49:21

SentinelHystrixtimeout

2022-07-13 08:16:49

RocketMQRPC日志
点赞
收藏

51CTO技术栈公众号