许多新手对Python的自动化脚本不是很清楚。为了帮助大家解决这个问题,下面小编就为大家详细讲解一下。需要的人可以从中学习,希望你能有所收获。
前言:
你有没有注意到,你可能每天都会执行很多重复的任务,比如阅读pdf、播放音乐、打开书签、清理文件夹等等?
我将分享四个有用的python自动化脚本,它们非常方便,无需一次又一次地手动完成这些任务。
00-1010脚本可以把pdf转换成音频文件,而且原理很简单。首先,用PyPDF从pdf中提取文本,然后用Pyttsx3将文本转换为语音。您也可以阅读这篇关于文本到语音转换的文章。
FastAPI:很快开发了一个文本到语言的界面。
代码如下:
importpyttsx3,PyPDF2
pdfreader=PyPDF2。pdffilerreader(open(' story . pdf ',' rb ')
speaker=pyttsx3.init()
for page _ numericrange(PD freader . numpages):
text=PD freader . Getpage(page _ num)。extract text()# #从hePDF中提取文本
cleaned_text=text.strip()。替换(' \n ',' ')# #删除不必要的空间和特征线
print(cleaned _ text)# # printTextFromPdF
# speaker . say(clean _ text)# # LetTheSpeakerSpeakTheText
speaker . save _ to _ file(cleaned _ text,' story . MP3 ')# # SavingTextInaaudiofile ' story . MP3 '
speaker.runAndWait()
脚本speaker.stop()
1、将 PDF 转换为音频文件
从歌曲文件夹中随机选择一首歌曲播放。需要注意的是,os.startfile只支持Windows系统。
导入随机,操作系统
music _ dir=' g : \ new English songs '
songs=os.listdir(music_dir)
song=random.randint(0,len(songs))
打印(歌曲[歌曲])# #打印歌曲名称
OS . start file(OS . path . join(music _ dir,songs[0])
2、从列表中播放随机音乐
每天睡觉前,我都会在网上搜索一些好的内容,第二天再看。很多时候我都会给遇到的网站或者文章做书签,但是我的书签每天都在增加,以至于现在我的浏览器周围有100多个书签。因此,在python的帮助下,我想出了另一种方法来解决这个问题。现在,我将这些网站的链接复制粘贴到一个文本文件中。每天早上,我都会运行一个脚本,在浏览器中再次打开所有这些网站。
importwebbrowser
wi
th open('./websites.txt') as reader:
for link in reader:
webbrowser.open(link.strip())
代码用到了 webbrowser,是 Python 中的一个库,可以自动在默认浏览器中打开 URL。
4、清理下载文件夹
世界上最混乱的事情之一是开发人员的下载文件夹,里面存放了很多杂乱无章的文件,此脚本将根据大小限制来清理您的下载文件夹,
有限清理比较旧的文件:
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.230890.com/zhan/153804.html
