0
点赞
收藏
分享

微信扫一扫

我们应该知道的 Python 自动化脚本

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


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


 

我们应该知道的 Python 自动化脚本_API


如何使 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")

首先,你需要为这个自动化安装 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]))

该代码进入包含所有你想播放的歌曲的音乐目录,并将它们全部放在一个列表中。然后它随机地一首接一首地播放每首歌曲。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')

你需要用 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)

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


 


自动视频下载器

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


import pytube

  
link = input('Youtube Video URL')

video_download = pytube.Youtube(link)

video_download.streams.first().download()

print('Video Downloaded', link)

pytube 库是一个非常简单的库,你可以用来下载视频到你的本地电脑。你所需要做的就是输入视频的链接,然后用 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()

 

如何自动转换图像为 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")]))

如何转换多张图像为 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")

这里我们使用 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)

如何生成短 URL

大的 URL 在阅读和分享时可能相当烦人。为了缩短 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

'''

   


 

网速测试器

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}")

虽然有 fast.com 这样的替代品,但有了这个脚本,你可以用 Python 脚本快速检查网速。


 


总结

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

举报

相关推荐

0 条评论