您当前的位置:首页 > 电脑百科 > 程序开发 > 语言 > Python

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

时间:2021-12-02 09:11:52  来源:  作者:XSJ

每天你都可能会执行许多重复的任务,例如阅读 pdf、播放音乐、查看天气、打开书签、清理文件夹等等,使用自动化脚本,就无需手动一次又一次地完成这些任务,非常方便。而在某种程度上,Python/ target=_blank class=infotextkey>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) 

运行结果如下所示:

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

 

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个实用的 Python 自动化脚本,你学会了吗?

 

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://www.tuicool.com/articles/EnYzmuE



Tags:Python 自动化   点击:()  评论:()
声明:本站部分内容及图片来自互联网,转载是出于传递更多信息之目的,内容观点仅代表作者本人,如有任何标注错误或版权侵犯请与我们联系(Email:2595517585@qq.com),我们将及时更正、删除,谢谢。
▌相关推荐
每天你都可能会执行许多重复的任务,例如阅读 pdf、播放音乐、查看天气、打开书签、清理文件夹等等,使用自动化脚本,就无需手动一次又一次地完成这些任务,非常方便。而在某种程度...【详细内容】
2021-12-02  Tags: Python 自动化  点击:(107)  评论:(0)  加入收藏
▌简易百科推荐
近几年 Web3 被炒得火热,但是大部分人可能还不清楚什么是 Web3,今天就让w3cschool编程狮小师妹带你了解下 Web3 是什么?与我们熟知的 Web1 和 Web2 又有什么区别呢?web3.0什么是...【详细内容】
2022-07-15  编程狮W3Cschool    Tags:Web3.0   点击:(2)  评论:(0)  加入收藏
1、让我们一起来看下吧,直接上图。 第一眼看到是不是觉得很高逼格,暗黑画风,这很大佬。其实它就是------AidLearning。一个运行在安卓平台的linux系统,而且还包含了许多非常强大...【详细内容】
2022-07-15  IT智能化专栏    Tags:AidLearning   点击:(2)  评论:(0)  加入收藏
真正的大师,永远都怀着一颗学徒的心! 一、项目简介 今天说的这个软件是一款基于Python+vue的自动化运维、完全开源的云管理平台。二、实现功能 基于RBAC权限系统 录像回放 ...【详细内容】
2022-07-14  菜鸟程序猿    Tags:Python   点击:(3)  评论:(0)  加入收藏
前言今天笔者想和大家来聊聊python接口自动化的MySQL数据连接,废话不多说咱们直接进入主题吧。 一、什么是 PyMySQL?PyMySQL是在Python3.x版本中用于连接MySQL服务器的一个库,P...【详细内容】
2022-07-11  测试架构师百里    Tags:python   点击:(19)  评论:(0)  加入收藏
aiohttp什么是 aiohttp?一个异步的 HTTP 客户端\服务端框架,基于 asyncio 的异步模块。可用于实现异步爬虫,更快于 requests 的同步爬虫。安装pip install aiohttpaiohttp 和 r...【详细内容】
2022-07-11  VT漫步    Tags:aiohttp   点击:(15)  评论:(0)  加入收藏
今天我们学习下 Queue 的进阶用法。生产者消费者模型在并发编程中,比如爬虫,有的线程负责爬取数据,有的线程负责对爬取到的数据做处理(清洗、分类和入库)。假如他们是直接交互的,...【详细内容】
2022-07-06  VT漫步    Tags:Python Queue   点击:(34)  评论:(0)  加入收藏
继承:是面向对象编程最重要的特性之一,例如,我们每个人都从祖辈和父母那里继承了一些体貌特征,但每个人却又不同于父母,有自己独有的一些特性。在面向对象中被继承的类是父类或基...【详细内容】
2022-07-06  至尊小狸子    Tags:python   点击:(25)  评论:(0)  加入收藏
点击上方头像关注我,每周上午 09:00准时推送,每月不定期赠送技术书籍。本文1553字,阅读约需4分钟 Hi,大家好,我是CoCo。在上一篇Python自动化测试系列文章:Python自动化测试之P...【详细内容】
2022-07-05  CoCo的软件测试小栈    Tags:Python   点击:(27)  评论:(0)  加入收藏
第一种方式:res = requests.get(url, params=data, headers = headers)第二种方式:res = requests.get(url, data=data, headers = headers)注意:1.url格式入参只支持第一种方...【详细内容】
2022-07-05  独钓寒江雪之IT    Tags:Python request   点击:(19)  评论:(0)  加入收藏
什么是python类的多态python的多态,可以为不同的类实例,或者说不同的数据处理方式,提供统一的接口。用比喻的方式理解python类的多态比如,同一个苹果(统一的接口)在孩子的眼里(类实...【详细内容】
2022-07-04  写小说的程序员    Tags:python类   点击:(28)  评论:(0)  加入收藏
站内最新
站内热门
站内头条