Petru Porumbescu

0 %
Petru Porumbescu
AWS Certified Developer & Solutions Architect | Python | Git & GitHub | Terraform | Docker
  • Residence:
    United Kingdom
  • Age:
    35
Licenses & Certifications:
  • AWS Certified Developer
  • AWS Certified Solutions Architect
  • HashiCorp Terraform Associate
  • Python for Beginners
  • Pythonic Programming
  • Developing on AWS
  • Python-based Microservices
English
Romanian
Skills:
  • Amazon Web Services (AWS)
  • Cloud Computing
  • Python Programming
  • Docker
  • Terraform
  • Git and Github
  • Linux, Windows, MacOS
  • WordPress
  • Microsoft Office Suite
  • Microsoft 365
  • Microsoft Teams
  • Slack
  • Leadership
  • Communication
  • Troubleshooting
  • Teamwork & Collaboration

Python Automation Scripts You Should Know

October 4, 2023

Introduction:

Python is a powerful and versatile programming language that can be used for various tasks, including automation. Python automation scripts can automate repetitive tasks, save time and effort, and improve productivity.

There are many different types of Python automation scripts, such as web scraping, data processing, and system administration. Some common examples of Python automation scripts include:

  • Web scraping scripts: These scripts can be used to extract data from websites, such as product prices, customer reviews, or stock market data.
  • Data processing scripts: These scripts can be used to clean, analyze, and visualize data.
  • System administration scripts: These scripts can be used to automate tasks such as backing up files, managing users, or deploying software.

1. Proofreading script:

This script uses the lmproof library to proofread text for grammar and spelling errors. It is a simple script to use, and it can be helpful for writers, students, and anyone else who needs to proofread their work.

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

First, you’ll need to install the lmproof library for this automation. Then, you can use the function proofread() which takes in text as a parameter. The function runs and prints the original text that was passed into the function, as well as the corrected text. You can use it to proofread an essay or a short article quickly.

2. Music player script:

This script uses the random and os modules to randomly play a song from a folder of music files. It is a simple script to use, and it can be helpful for people who want to listen to music without manually selecting a song.

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])) 

The code goes to the music directory containing all the songs you want to play and puts them all in a list. Then, it randomly plays each song one after the other. The os.startfile plays the song.

3. PDF to CSV converter script:

This script uses the tabula library to convert PDF data to CSV data. CSV files are easier to manipulate and analyse than PDF files, so this script can be helpful for people who need to work with data from PDF files.

import tabula

filename = input("Enter File Path: ")
df = tabula.read_pdf(filename, encoding='utf-8', spreadsheet=True, pages='1')

df.to_csv('output.csv')

You’ll need to install the tabula library using pip to run this code. After installation, you can pass the file into your project.

The library comes with a function read_pdf() which takes the file and reads it. You finish the automation by using the to_csv() function to convert the output into CSV.

4. Image compressor script:

This script uses the PIL library to compress images. Compressing images can reduce their file size without sacrificing too much quality. This can be helpful for people who need to share images online or store them on devices with limited storage space.

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)

You can manipulate images using the Python Imaging Library (PIL). It supports adding filters, blurring, sharpening, smoothing, edge detection, compression, and more.

5. YouTube video downloader script:

This script uses the pytube library to download YouTube videos. This can be helpful for people who want to watch YouTube videos offline or save them for later viewing.

import pytube

link = input('Youtube Video URL')
video_download = pytube.Youtube(link)
video_download.streams.first().download()
print('Video Downloaded', link)

Downloading YouTube videos to your local computer is made easy with the help of the Pytube library. Input the video link and use the “download()” method to complete the download process.

6. Text-to-speech script:

We will use the Google Text-to-Speech API for this script. The API is up to date and works with many languages, pitches, and voices that you can select from.

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()

7. Image to PDF converter script:

This script uses the img2pdf library to convert images to PDFs. PDF files are more portable and secure than image files, so this script can be helpful for people who need to share or store images in a PDF format.

How to convert a single image to a 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")]))

How to convert multiple images to 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")

Here, we’re using the image2pdf library in Python to convert our image to a PDF. We can also convert multiple images to PDFs with just a few lines of code.

8. Plagiarism checker script:

This script uses the difflib library to check for plagiarism between two files. This can be helpful for students, writers, and anyone else who needs to check their work for plagiarism.

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)

9. URL shortener script:

This script uses a third-party API to shorten URLs. Short URLs are more accessible to share and remember than long URLs, so this script can be helpful for people who need to share URLs online.

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

'''

10. Internet speed tester script:

The OOKLA speed test API lets you check internet speed, including ping, download, and upload speeds.

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

Conclusion:

In this article, we have talked about ten Python automation scripts. These scripts can be used to automate a wide variety of tasks, saving time and effort and improving productivity.

I encourage you to explore these scripts and learn how to use them. There are many other Python automation scripts available online, so be sure to do some research and find scripts that meet your specific needs.

Posted in Python
Write a comment