13 Fun Advanced Python Scripts

Every day we face many programming challenges that require advanced coding. You can't solve these problems with simple basic Python syntax.

In this article, I'll share 13 advanced Python scripts that can be handy tools in your projects. If you don't use these scripts yet, you can add them to your favorites for later use.

Ok, let's get started now.

Technology Exchange

Technology must learn to share and communicate, and it is not recommended to work behind closed doors. One person can go fast, and a group of people can go farther.

Good articles are inseparable from the sharing and recommendation of fans, dry data, data sharing, data, and technical exchange improvement, all of which can be obtained by adding the communication group. The group has more than 2,000 friends. The best way to add notes is: source + interest directions, making it easy to find like-minded friends.

Method ①, add WeChat account: pythoner666, remarks: from CSDN + add group
Method ②, WeChat search official account: Python learning and data mining, background reply: add group

1. Speed ​​test with Python

This advanced script helps you test your Internet speed using Python. Just install the speed test module and run the code below.

# pip install pyspeedtest
# pip install speedtest
# pip install speedtest-cli
#method 1
import speedtest
speedTest = speedtest.Speedtest() 
print(speedTest.get_best_server())
#Check download speed
print(speedTest.download())
#Check upload speed
print(speedTest.upload())
# Method 2
import pyspeedtest
st = pyspeedtest.SpeedTest()
st.ping()
st.download()
st.upload()

2. Search on Google

You can extract the redirect URL from Google search engine, install the below mentioned modules and follow the code.

# pip install google
from googlesearch import search
query = "Medium.com"

for url in search(query):
    print(url)

3. Make a web robot

This script will help you automate your website using Python. You can build a web bot that can control any website. Check out the code below, this script is handy in web scraping and web automation.

# pip install selenium
import time
from selenium import webdriver
from selenium.webdriver.common.keys 
import Keysbot = webdriver.Chrome("chromedriver.exe")
bot.get('http://www.google.com')
search = bot.find_element_by_name('q')
search.send_keys("@codedev101")
search.send_keys(Keys.RETURN)
time.sleep(5)
bot.quit()

4. Get song lyrics

This advanced script will show you how to get lyrics from any song. First, you have to get a free API key from the Lyricsgenius website, then, you have to follow the code below.

# pip install lyricsgenius
import lyricsgenius
api_key = "xxxxxxxxxxxxxxxxxxxxx"
genius = lyricsgenius.Genius(api_key)
artist = genius.search_artist("Pop Smoke", 
max_songs=5,sort="title")
song = artist.song("100k On a Coupe")
print(song.lyrics)

5. Get the Exif data of the photo

Use the Python Pillow module to get Exif data for any photo. Check out the code mentioned below. I provide two methods to extract Exif data of photos.

# Get Exif of Photo
# Method 1
# pip install pillow
import PIL.Image
import PIL.ExifTags
img = PIL.Image.open("Img.jpg")
exif_data = 
{
    
    
    PIL.ExifTags.TAGS[i]: j
    for i, j in img._getexif().items()
    if i in PIL.ExifTags.TAGS
}
print(exif_data)
# Method 2
# pip install ExifRead
import exifread
filename = open(path_name, 'rb')
tags = exifread.process_file(filename)
print(tags)

6. Extract OCR text from image

OCR is a method of recognizing text from digital and scanned documents. Many developers use it to read handwritten data, the following Python code can convert scanned images to OCR text format.

NOTE: You must download tesseract.exe from Github

# pip install pytesseract
import pytesseract
from PIL import Image

pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

t=Image.open("img.png")
text = pytesseract.image_to_string(t, config='')
print(text)

7. Convert Photo to Cartonize

This simple high-level script will convert your photos to Cartonize format. Check out the sample code below and try it out.

# pip install opencv-python
import cv2

img = cv2.imread('img.jpg')
grayimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
grayimg  = cv2.medianBlur(grayimg, 5)

edges = cv2.Laplacian(grayimg , cv2.CV_8U, ksize=5)
r,mask =cv2.threshold(edges,100,255,cv2.THRESH_BINARY_INV)
img2 = cv2.bitwise_and(img, img, mask=mask)
img2 = cv2.medianBlur(img2, 5)

cv2.imwrite("cartooned.jpg", mask)

8. Empty the Recycle Bin

This simple script lets you empty your recycle bin in Python, check out the code below to see how.

# pip install winshell
import winshell
try:
    winshell.recycle_bin().empty(confirm=False, /show_progress=False, sound=True)
    print("Recycle bin is emptied Now")
except:
    print("Recycle bin already empty")

9. Python image enhancement

Enhance your photos to look better with the Python Pillow library. In the code below, I have implemented four methods to enhance any photo.

# pip install pillow
from PIL import Image,ImageFilter
from PIL import ImageEnhance

im = Image.open('img.jpg')

# Choose your filter
# add Hastag at start if you don't want to any filter below
en = ImageEnhance.Color(im)
en = ImageEnhance.Contrast(im)
en = ImageEnhance.Brightness(im)
en = ImageEnhance.Sharpness(im)# result
en.enhance(1.5).show("enhanced")

10. Get the Windows version

This simple script will help you get the full windows version you are currently using.


# Window Versionimport wmi
data = wmi.WMI()
for os_name in data.Win32_OperatingSystem():
  print(os_name.Caption)
# Microsoft Windows 11 Home

11. Convert PDF to Image

Use the following code to convert all Pdf pages to images.

# PDF to Images
import fitz
pdf = 'sample_pdf.pdf'
doc = fitz.open(pdf)

for page in doc:
    pix = page.getPixmap(alpha=False)
    pix.writePNG('page-%i.png' % page.number)

12. Conversion: Hexadecimal to RGB

This script will simply convert Hex to RGB. Check out the sample code below.

# Conversion: Hex to RGB
def Hex_to_Rgb(hex):
    h = hex.lstrip('#')
    return tuple(int(h[i:i+2], 16) for i in (0, 2, 4))
print(Hex_to_Rgb('#c96d9d'))  # (201, 109, 157)
print(Hex_to_Rgb('#fa0515')) # (250, 5, 21)

13. Website status

You can use Python to check if a website is working properly. Check the code below, if it shows 200, it means the website is up, if it shows 404, it means the website is down.

# pip install requests
#method 1
import urllib.request
from urllib.request import Request, urlopenreq = Request('https://medium.com/@pythonians', headers={
    
    'User-Agent': 'Mozilla/5.0'})
webpage = urlopen(req).getcode()
print(webpage)  # 200
# method 2
import requests
r = requests.get("https://medium.com/@pythonians")
print(r.status_code) # 200

Guess you like

Origin blog.csdn.net/m0_59596937/article/details/131147512