• 你应该知道的 Python 自动化脚本


    我们都有一些需要重复做的任务。幸运的是,我们可以将其中一些过程自动化,这样我们就可以专注于做其他真正需要精力和注意力的事情。

    在这篇文章中,我们将谈论一些 Python 自动化脚本,你可以轻松地用它们来执行自动化任务。重要的是要明白,它们都是现成的代码,可以帮助我们处理许多日常的重复性任务。

    我强烈建议你在继续学习本文之前,先对 Python 编程语言有一些了解。

    可以开始了吗?

    如何使 Python 校对自动化

    列表中的第一个是校对。每当你想消除写作中的语法和拼写错误时,你可以试试这个使用 Lmproof 模块的项目。

    # Python Proofreading
    # pip install lmproof
    import lmproof
    def proofread(text):
        proofread = lmproof.load("en")
        correction = proofread.proofread(text)
        print("Original: {}".format(text))
        print("Correction: {}".format(correction))
        
    proofread("Your Text")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    首先,你需要为这个自动化安装 lmproof 库。然后,你可以使用函数 proofread(),它接收 text 作为参数。该函数运行并打印传入该函数的原始文本以及更正后的文本。你可以用它来快速校对一篇论文或一篇短文。

    如何自动播放随机音乐

    在工作时,许多开发人员喜欢听音乐。因此,对于音乐爱好者(比如我)来说,这个脚本会从包含歌曲的文件夹中随机挑选一首歌曲,并在 Python 中的 OS 和 random 模块的帮助下播放。

    import random, os
    music_dir = 'E:\\music diretory'
    songs = os.listdir(music_dir)
    
    song = random.randint(0,len(songs))
    
    # Prints The Song Name
    print(songs[song])  
    
    os.startfile(os.path.join(music_dir, songs[0])) 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    该代码进入包含所有你想播放的歌曲的音乐目录,并将它们全部放在一个列表中。然后它随机地一首接一首地播放每首歌曲。os.startfile 播放歌曲。

    自动 PDF-CSV 转换器

    有时你需要将 pdf 数据转换为 CSV(comma separated value 逗号分隔值)数据,这样你就可以用它进行进一步的分析。在这些情况下,这个脚本可以派上用场。

    import tabula
    
    filename = input("Enter File Path: ")
    df = tabula.read_pdf(filename, encoding='utf-8', spreadsheet=True, pages='1')
    
    df.to_csv('output.csv')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    你需要用 pip 安装 tabula 库,以便运行这段代码。安装后,你可以将文件传入你的项目。

    库中有一个函数 read_pdf(),它接收文件并读取它。你通过使用 to_csv() 函数将输出转换为 CSV 来完成自动化。

    自动照片压缩器

    你也可以通过压缩来减少图片的大小——同时仍然保持其质量。

    import PIL
    from PIL import Image
    from tkinter.filedialog import *
    
    fl=askopenfilenames()
    img = Image.open(fl[0])
    img.save("output.jpg", "JPEG", optimize = True, quality = 10)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    你可以使用 PIL(Python Imaging Library)来处理图像,对图像做很多事情,例如添加滤镜、模糊、锐化、平滑、边缘检测、压缩图像。

    自动 YouTube 视频下载器

    这里有一个简单的自动脚本,用于下载 YouTube 视频。只需使用下面的代码就可以下载任何视频,不需要任何网站或应用程序。

    import pytube
    
    link = input('Youtube Video URL')
    video_download = pytube.Youtube(link)
    video_download.streams.first().download()
    print('Video Downloaded', link)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    pytube 库是一个非常简单的库,你可以用来下载 YouTube 视频到你的本地电脑。你所需要做的就是输入视频的链接,然后用 download() 方法将其下载到你的电脑上。

    自动文本转语音

    我们将在这个脚本中使用谷歌文本转语音 API。该 API 是最新的,可用于许多语言、音调和声音,你可以从中选择。

    from pygame import mixer
    from gtts import gTTS
    
    def main():
       tts = gTTS('Like This Article')
       tts.save('output.mp3')
       mixer.init()
       mixer.music.load('output.mp3')
       mixer.music.play()
       
    if __name__ == "__main__":
       main()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    如何自动转换图像为 PDF

    这是一个非常常见的任务,你可能经常执行。你可能想转换一张或多张图像为一个 PDF。

    如何转换一张图像为 PDF:

    import os
    import img2pdf
    with open("output.pdf", "wb") as file:
       file.write(img2pdf.convert([i for i in os.listdir('path to image') if i.endswith(".jpg")]))
    
    • 1
    • 2
    • 3
    • 4

    如何转换多张图像为 PDF:

    from fpdf import FPDF
    Pdf = FPDF()
    
    list_of_images = ["wall.jpg", "nature.jpg","cat.jpg"]
    for i in list_of_images:
       Pdf.add_page()
       Pdf.image(i,x,y,w,h)
       Pdf.output("result.pdf", "F")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    这里我们使用 Python 中的 image2pdf 库将我们的图像转换为 PDF。我们也可以只用几行代码就把多张图像转换为 PDF。

    自动抄袭检查器

    抄袭是将他人的文字或想法作为自己的,无论是否得到他人的许可,将其整合到你的作品中而不注明原作者。

    当你想在两个文件之间检查抄袭时,这个脚本会很有帮助。

    from difflib import SequenceMatcher
    def plagiarism_checker(f1,f2):
        with open(f1,errors="ignore") as file1,open(f2,errors="ignore") as file2:
            f1_data=file1.read()
            f2_data=file2.read()
            res=SequenceMatcher(None, f1_data, f2_data).ratio()
            
    print(f"These files are {res*100} % similar")
    f1=input("Enter file_1 path: ")
    f2=input("Enter file_2 path: ")
    plagiarism_checker(f1, f2)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    如何生成短 URL

    大的 URLs 在阅读和分享时可能相当烦人。为了缩短 URL,这个脚本利用了一个第三方的 API。

    from __future__ import with_statement
    import contextlib
    try:
    	from urllib.parse import urlencode
    except ImportError:
    	from urllib import urlencode
    try:
    	from urllib.request import urlopen
    except ImportError:
    	from urllib2 import urlopen
    import sys
    
    def make_tiny(url):
    	request_url = ('http://tinyurl.com/app-index.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()
        
    
    '''
    
    -----------------------------OUTPUT------------------------
    python url_shortener.py https://www.wikipedia.org/
    https://tinyurl.com/bif4t9
    
    '''
        
    
    • 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

    网速测试器

    OOKLA 速度检测 API 允许你检查 ping 和网速。除了检查 ping 之外,这个小的自动化项目还可以检查下载和上传速度。

    # Internet Speed tester
    # pip install speedtest-cli
    import speedtest as st
    
    # Set Best Server
    server = st.Speedtest()
    server.get_best_server()
    
    # Test Download Speed
    down = server.download()
    down = down / 1000000
    print(f"Download Speed: {down} Mb/s")
    
    # Test Upload Speed
    up = server.upload()
    up = up / 1000000
    print(f"Upload Speed: {up} Mb/s")
    
    # Test Ping
    ping = server.results.ping
    print(f"Ping Speed: {ping}")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    虽然有 fast.com 这样的替代品,但有了这个脚本,你可以用 Python 脚本快速检查网速。
    我的职业生涯开始和大多数码农一样,刚开始接触都是最基础的软件测试、编程语法。那时候在B站CSDN到处找学习资源,在这个吃技术的IT行业来说

    ,不断学习是至关重要的。但是我之前做的是最基础的业务工作,随着时间的消磨,让我产生了对自我价值和岗位意义的困惑。

    我的程序员之路,一路走来都离不开每个阶段的计划,因为自己喜欢规划和总结,所以,我和朋友特意花了一段时间整理编写了下面的《python架构师

    学习路线》,也整理了不少【网盘资源】,需要的朋友可以公众号【Python大本营】获取网盘链接。
    希望会给你带来帮助和方向。

    总结

    我们在这篇文章中谈到了十个 Python 自动化脚本,我希望你觉得它很有用。你也可以去看看所使用的库,拓展你的知识。

  • 相关阅读:
    Apifox下载安装【官方版】
    C#.Net筑基-集合知识全解
    【SQL】SQLAlchemy:如何使用Python ORM框架来操作MySQL?
    农产品行业的春天来了,乘风破浪颠覆传统营销,实现一户带一户,共同致富,这套农产品生态方案可收藏借鉴
    【Python】练习题附带答案
    TinyWebServer学习笔记-threadpool
    Redis集群高频问答,连夜肝出来了
    Jtti:Linux大文件重定向和管道的效率哪个更高
    基于Elasticsearch + Fluentd + Kibana(EFK)搭建日志收集管理系统
    JavaScript学习(二)——基本对象
  • 原文地址:https://blog.csdn.net/weixin_47197994/article/details/133914500