6个实用的 Python 自动化脚本,告别加班,你学会了吗?

每天你都可能会执行许多重复的任务,例如阅读 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() 

🌲🌲🌲 好啦,这就是今天要分享给大家的全部内容了
❤️❤️❤️如果你喜欢的话,就不要吝惜你的一键三连了~

 

  • 33
    点赞
  • 363
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
BurnInTest是一款自动化测试工具,用于对软件和硬件系统进行负载和压力测试。它可以帮助开发人员和测试人员识别潜在的性能问题、内存泄漏、线程冲突等,以确保系统在高负载情况下的稳定性和可靠性。 自动化脚本在BurnInTest中扮演着重要的角色,它们可以自动执行一系列预定义的测试任务,从而减少人工干预的需求。以下是一些关于BurnInTest自动化脚本的介绍: 1. 脚本类型:BurnInTest支持多种类型的自动化脚本,包括Python、JavaScript、VBScript等。这允许用户根据自己熟悉的编程语言来编写和执行测试脚本。 2. 脚本编写:用户可以在BurnInTest的脚本编辑器中编写自动化脚本。编辑器提供了代码提示、语法检查等功能,帮助用户更轻松地编写和维护脚本。 3. 脚本执行:在BurnInTest中,用户可以通过运行自动化脚本来启动和控制测试过程。脚本可以设置测试参数、调度任务、收集结果等。 4. 结果分析:自动化脚本还可以用于分析测试结果,例如检查系统性能指标是否达到预期范围,或者检测是否有异常行为发生。 5. 集成与扩展:BurnInTest的自动化脚本可以与其他工具和框架集成,例如持续集成系统(CI)或缺陷跟踪系统。此外,用户还可以通过编写自定义插件来扩展BurnInTest的功能。 总之,BurnInTest的自动化脚本功能可以帮助用户更高效地进行软件和硬件系统的负载和压力测试,确保系统在各种条件下的稳定性和可靠性。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值