更具新闻影响力网站
欢迎投稿本网站
主页 > Python脚本 > Python自动化脚本

6个实用的Python自动化脚本详解

发布时间:2022-05-01 08:38   来源:网络    作者:小编

6个实用的Python自动化脚本详解

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

1、将 PDF 转换为音频文件

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

代码如下:

1
2
3
4
5
6
7
8
9
10
11
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 系统。

1
2
3
4
5
6
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的帮助下,我想出了另一种方法来解决这个问题。现在,我把这些网站的链接复制粘贴到文本文件中,每天早上我都会运行脚本,在我的浏览器中再次打开所有这些网站。

1
2
3
4
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上海徐汇区对应的天气网址。 

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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变得非常恼火,很难阅读和共享,此脚可以将长网址变为短网址。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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、清理下载文件夹

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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()

到此这篇关于6个实用的Python自动化脚本详解的文章就介绍到这了,更多相关Python自动化脚本内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!


上一篇:暂无
下一篇:分享4个方便且好用的Python自动化脚本

分享到:
0
最新资讯
阅读排行
广告位