avatarJIN

Summary

This context provides 13 fun Python scripts for various tasks, such as performing an internet speed test, searching on Google, creating a web robot, fetching lyrics from any song, retrieving Exif data from images, converting photos into a cartoonized format, emptying the Recycle Bin, enhancing the quality of photos, retrieving the current Windows version, converting each page of a PDF document into separate images, converting from Hexadecimal to RGB color format, and checking the status of a website.

Abstract

The context offers a collection of 13 Python scripts that cater to different programming challenges beyond basic syntax. These scripts serve as valuable tools for various projects, including internet speed tests, Google searches, web automation, song lyrics extraction, image manipulation, system maintenance, image enhancement, OS version retrieval, PDF conversion, color format conversion, and website status checks. Each script is explained with code snippets and examples, making it easy for users to understand and implement them in their projects.

Opinions

  • The author believes that these scripts go beyond the fundamentals and can be valuable additions to any programmer's collection.
  • The author encourages users to consider adding these scripts to their collection for future use.
  • The author expresses their passion for sharing knowledge and helping others learn.
  • The author seeks support from users in the form of referred membership to continue creating content that makes a difference in people's lives.
  • The author provides detailed explanations and examples for each script, making it easy for users to understand and implement them.
  • The author emphasizes the importance of accurate results in the OCR script by ensuring the necessary dependencies are installed and the Tesseract OCR engine is properly configured.
  • The author encourages users to adjust the enhancement factor in the image enhancement script to control the intensity of the enhancement.
Photo by Faisal on Unsplash

13 Fun Python Scripts

Add Excitement to Your Coding Adventures with These Engaging Python Scripts!

Thank you for being a part of this journey with me, and I hope to continue providing value to you for years to come! Giving tips by supporting me.

Hello friend, I hope you’re doing well! I’m writing to you today because I am truly passionate about sharing my knowledge and helping others learn. If you’ve found my articles to be valuable and they’ve made a positive impact on your life, I would be overjoyed if you could support me as a referred member. Your support not only helps me financially but also motivates me to continue creating content that makes a difference in people’s lives. Thank you from the bottom of my heart for considering supporting me. It means the world to me to have your support on this journey.

Every day, we encounter numerous programming challenges that demand advanced coding techniques beyond basic Python syntax. In this article, I will introduce 13 fun Python scripts that serve as valuable tools for your projects. These solutions go beyond the fundamentals, and if you haven’t already, consider adding them to your collection for future use.

  1. Speed ​​test with Python

To conduct an Internet speed test

# First, you need to install the required module.
# You can choose any of the following options:
# pip install pyspeedtest
# pip install speedtest
# pip install speedtest-cli

import speedtest
import pyspeedtest

def test_internet_speed():
    # Using speedtest module
    speed_test = speedtest.Speedtest()
    best_server = speed_test.get_best_server()
    print(f"Best server: {best_server['host']} located in {best_server['country']}")

    download_speed = speed_test.download() / 1_000_000  # Convert to Mbps
    print(f"Download speed: {download_speed:.2f} Mbps")

    upload_speed = speed_test.upload() / 1_000_000  # Convert to Mbps
    print(f"Upload speed: {upload_speed:.2f} Mbps")

    # Using pyspeedtest module
    pst = pyspeedtest.SpeedTest()
    ping_speed = pst.ping()
    print(f"Ping speed: {ping_speed} ms")

if __name__ == "__main__":
    test_internet_speed()

This script imports both speedtest and pyspeedtest modules and defines a function test_internet_speed() to perform the speed test. The script then executes the function to display the results for download speed, upload speed, and ping speed, along with information about the best server for the test.

2. Search on Google

To perform a Google search and extract the redirect URLs, you can utilize the “Google” library.

# Ensure you have installed the "google" library using the following command:
# pip install google

from googlesearch import search

def extract_redirect_urls(query):
    search_results = search(query, num_results=10, lang="en", stop=10, pause=2.0)
    
    for url in search_results:
        print(url)

if __name__ == "__main__":
    search_query = "Python"
    extract_redirect_urls(search_query)

We import the “google search” library and define a function called extract_redirect_urls(query) to perform the Google search. The function takes a search query as input and extracts the top 10 redirect URLs from the search results. We then call this function with a sample search query "Python programming language" to demonstrate the functionality.

3. Create a Web Robot

To automate website interactions with ease

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

def web_robot():
    # Initialize the Chrome web driver
    bot = webdriver.Chrome("chromedriver.exe")

    # Open Google's homepage
    bot.get('http://www.google.com')

    # Locate the search input field and enter the desired search query
    search = bot.find_element_by_name('q')
    search.send_keys("@Python)

    # Perform the search by hitting the Enter key
    search.send_keys(Keys.RETURN)

    # Wait for the results to load (you can adjust the sleep duration as needed)
    time.sleep(5)

    # Close the web driver
    bot.quit()

if __name__ == "__main__":
    web_robot()

This code block includes the necessary instructions to set up the web robot using the “selenium” module. It opens Google’s homepage, enters the search query “@Python,” performs the search, waits for the results to load, and finally, quits the web driver. You can extend and customize this script for various web automation and scraping tasks.

4. Fetch lyrics from any song

Need a free API key from the Lyricsgenius website

# Ensure you have installed the "lyricsgenius" module using the following command:
# pip install lyricsgenius

import lyricsgenius

def get_song_lyrics(api_key, artist_name, song_title):
    genius = lyricsgenius.Genius(api_key)
    artist = genius.search_artist(artist_name, max_songs=5, sort="title")
    song = artist.song(song_title)
    return song.lyrics

if __name__ == "__main__":
    # Replace "xxxxxxxxxxxxxxxxxxxxx" with your actual API key
    api_key = "xxxxxxxxxxxxxxxxxxxxx"
    
    # Replace "Pop Smoke" with the artist's name and "100k On a Coupe" with the song title
    artist_name = "Alan Walker"
    song_title = "Somebody like u"
    
    lyrics = get_song_lyrics(api_key, artist_name, song_title)
    print(lyrics)

We define a function get_song_lyrics(api_key, artist_name, song_title) to retrieve lyrics from any song. You need to provide your API key, the artist's name, and the song title as inputs to this function.

5. Retrieve Exif data from any photo

Method 1:

# Ensure you have installed the "Pillow" module using the following command:
# pip install pillow

import PIL.Image
import PIL.ExifTags

def get_exif_data_method1(image_path):
    img = PIL.Image.open(image_path)
    exif_data = {
        PIL.ExifTags.TAGS[i]: j
        for i, j in img._getexif().items()
        if i in PIL.ExifTags.TAGS
    }
    return exif_data

if __name__ == "__main__":
    image_path = "Img.jpg"  # Replace this with the actual path of your image
    exif_data = get_exif_data_method1(image_path)
    print(exif_data)

Method 2:

# Ensure you have installed the "ExifRead" module using the following command:
# pip install ExifRead

import exifread

def get_exif_data_method2(image_path):
    with open(image_path, 'rb') as file:
        tags = exifread.process_file(file)
    return tags

if __name__ == "__main__":
    image_path = "Img.jpg"  # Replace this with the actual path of your image
    exif_data = get_exif_data_method2(image_path)
    print(exif_data)

We provide two methods to extract Exif data from photos. Method 1 uses the “Pillow” module, while Method 2 uses the “ExifRead” module. You need to replace "Img.jpg" with the actual path of your image file. The scripts will then display the Exif data for the specified photo.

6. Extract OCR text from images

# Ensure you have installed the "pytesseract" module using the following command:
# pip install pytesseract

# Also, download and install the Tesseract OCR engine from Github and set the correct path below.

import pytesseract
from PIL import Image

# Set the path to the Tesseract OCR engine executable
pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

def extract_ocr_text(image_path):
    image = Image.open(image_path)
    ocr_text = pytesseract.image_to_string(image, config='')
    return ocr_text

if __name__ == "__main__":
    image_path = "img.png"  # Replace this with the actual path of your image file
    extracted_text = extract_ocr_text(image_path)
    print(extracted_text)

We use the “pytesseract” module to perform OCR on the specified image file. You need to set the correct path to the Tesseract OCR engine executable by replacing r'C:\Program Files\Tesseract-OCR\tesseract.exe' with the actual path on your system.

The script will then read the text content from the image and display it on the console. Make sure you have the necessary dependencies installed and the Tesseract OCR engine properly configured for accurate results.

7. Convert your photos into a cartonized format

# Ensure you have installed the "opencv-python" module using the following command:
# pip install opencv-python

import cv2

def convert_to_cartoon(image_path, output_path):
    img = cv2.imread(image_path)
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray_img = cv2.medianBlur(gray_img, 5)

    edges = cv2.Laplacian(gray_img, cv2.CV_8U, ksize=5)
    _, mask = cv2.threshold(edges, 100, 255, cv2.THRESH_BINARY_INV)
    cartooned_img = cv2.bitwise_and(img, img, mask=mask)
    cartooned_img = cv2.medianBlur(cartooned_img, 5)

    cv2.imwrite(output_path, cartooned_img)

if __name__ == "__main__":
    input_image_path = "img.jpg"  # Replace this with the actual path of your input image
    output_image_path = "cartooned.jpg"  # Replace this with the desired output path

    convert_to_cartoon(input_image_path, output_image_path)

We define a function convert_to_cartoon(image_path, output_path) that takes the path of the input image and the desired output path as arguments. The script then reads the input image, processes it to create a cartoonized version, and saves the result in the specified output path.

To use the script, replace "img.jpg" with the actual path of your input image and "cartooned.jpg" with the desired output path where the cartonized image will be saved. Running the script will generate the cartonized version of the input image.

8. Empty the Recycle Bin

import winshell

def empty_recycle_bin():
    try:
        winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=True)
        print("Recycle bin is now emptied.")
    except:
        print("Recycle bin is already empty.")

if __name__ == "__main__":
    empty_recycle_bin()

The function empty_recycle_bin() attempts to empty the Recycle Bin using the "winshell" module. If the operation is successful, it prints a message indicating that the Recycle Bin is now empty. Otherwise, if the Recycle Bin is already empty or any other error occurs during the process, it prints a corresponding message.

9. Enhance the quality of your photos

# Ensure you have installed the "pillow" module using the following command:
# pip install pillow

from PIL import Image, ImageEnhance

def enhance_photo(image_path, enhancement_type, enhancement_factor):
    im = Image.open(image_path)
    
    if enhancement_type == "color":
        enhancer = ImageEnhance.Color(im)
    elif enhancement_type == "contrast":
        enhancer = ImageEnhance.Contrast(im)
    elif enhancement_type == "brightness":
        enhancer = ImageEnhance.Brightness(im)
    elif enhancement_type == "sharpness":
        enhancer = ImageEnhance.Sharpness(im)
    else:
        print("Invalid enhancement type. Choose 'color', 'contrast', 'brightness', or 'sharpness'.")
        return
    
    enhanced_image = enhancer.enhance(enhancement_factor)
    enhanced_image.show("enhanced")

if __name__ == "__main__":
    image_path = "img.jpg"  # Replace this with the actual path of your image file
    
    # Choose your desired enhancement type and factor
    enhancement_type = "brightness"  # Change this to 'color', 'contrast', or 'sharpness'
    enhancement_factor = 1.5  # Adjust this value to control the enhancement intensity
    
    enhance_photo(image_path, enhancement_type, enhancement_factor)

We have created a function enhance_photo() that takes the image path, enhancement type (color, contrast, brightness, or sharpness), and enhancement factor as inputs. Based on the chosen enhancement type, the script applies the corresponding enhancement to the image using the Pillow library's ImageEnhance module. You can adjust the enhancement factor to control the intensity of the enhancement.

To use the script, replace "img.jpg" with the actual path of your image and adjust the enhancement_type and enhancement_factor variables to achieve the desired photo enhancement.

10. Retrieve the current Windows version

# Ensure you have installed the "wmi" module using the following command:
# pip install wmi

import wmi

def get_windows_version():
    data = wmi.WMI()
    for os_name in data.Win32_OperatingSystem():
        return os_name.Caption

if __name__ == "__main__":
    windows_version = get_windows_version()
    print(windows_version)

The get_windows_version() function utilizes the "wmi" module to access Windows Management Instrumentation (WMI) and retrieve information about the operating system. The script prints the full version of the current Windows operating system.

11. Convert each page of a PDF document into separate images

# Ensure you have installed the "PyMuPDF" module using the following command:
# pip install PyMuPDF

import fitz

def convert_pdf_to_images(pdf_path):
    doc = fitz.open(pdf_path)

    for page in doc:
        pix = page.getPixmap(alpha=False)
        output_filename = f"page-{page.number}.png"
        pix.writePNG(output_filename)

    doc.close()

if __name__ == "__main__":
    pdf_path = 'sample_pdf.pdf'  # Replace this with the actual path of your PDF file
    convert_pdf_to_images(pdf_path)

The function convert_pdf_to_images(pdf_path) opens the PDF file using PyMuPDF, iterates through each page, and converts it into a PNG image. The images are saved with filenames in the format "page-{page_number}.png", where "{page_number}" corresponds to the page number.

12. Convert from Hexadecimal to RGB color format

def hex_to_rgb(hex_value):
    hex_cleaned = hex_value.lstrip('#')
    return tuple(int(hex_cleaned[i:i+2], 16) for i in (0, 2, 4))

if __name__ == "__main__":
    hex_color1 = '#c96d9d'
    hex_color2 = '#fa0515'

    rgb_color1 = hex_to_rgb(hex_color1)
    rgb_color2 = hex_to_rgb(hex_color2)

    print(rgb_color1)  # Output: (201, 109, 157)
    print(rgb_color2)  # Output: (250, 5, 21)

The function hex_to_rgb(hex_value) performs the conversion by stripping the '#' symbol from the input Hexadecimal value and then converting the individual Hex values into their corresponding decimal values. The resulting RGB values are returned as a tuple.

13. Check the status of a website

# Ensure you have installed the "requests" module using the following command:
# pip install requests

import requests

def check_website_status(url):
    try:
        response = requests.get(url)
        status_code = response.status_code
        return status_code
    except requests.exceptions.RequestException:
        return 404

if __name__ == "__main__":
    website_url = "https://Youtube.com"  # Replace this with the URL of the website you want to check
    status_code = check_website_status(website_url)

    if status_code == 200:
        print("The website is up and running.")
    elif status_code == 404:
        print("The website is down or unavailable.")
    else:
        print(f"Unexpected status code: {status_code}")

The check_website_status(url) function uses the "requests" module to send an HTTP GET request to the specified website URL. It then retrieves the status code from the response. If the status code is 200, it indicates that the website is up and running. If the status code is 404, it means the website is down or unavailable. Any other status code is considered unexpected.

If you’ve found any of my articles helpful or useful then please consider throwing a coffee my way to help support my work or give me patronage😊, by using

Patreon

Ko-fi.com

buymeacoffee

Last but not least, if you are not a Medium Member yet and plan to become one, I kindly ask you to do so using the following link. I will receive a portion of your membership fee at no additional cost to you.

In Plain English

Thank you for being a part of our community! Before you go:

Python
Programming
Coding
Script
Tools
Recommended from ReadMedium