6个使用的Python脚本

81 篇文章 1 订阅
78 篇文章 1 订阅

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

每天你都可能会执行许多重复的任务,例如阅读 pdf、播放音乐、查看天气、打开书签、清理文件夹等等,使用自动化脚本,就无需手动一次又一次地完成这些任务,非常方便。快跟随小编一起试一试吧
每天你都可能会执行许多重复的任务,例如阅读 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('
',' ') ?## 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:

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

具体代码如下:

i

mport 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])?
? ? ?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值