Share 6 practical Python automation scripts

You may perform many repetitive tasks every day, such as reading pdf, playing music, viewing the weather, opening bookmarks, cleaning folders, etc. using automatic scripts, you don't need to complete these tasks again and again manually, which is very convenient. To some extent, Python is synonymous with automation. Share six very useful Python automation scripts today.

1. Convert PDF to audio file

The script can convert pdf into audio file. The principle is also very simple. First, use PyPDF to extract the text in pdf, and then use Pyttsx3 to convert the text to voice. You can also read this article about text to speech FastAPI: quickly develop a text to voice interface.

The code is as follows:

import pyttsx3,PyPDF2
pdfreader = PyPDF2.PdfFileReader(open('story.pdf','rb'))
speaker = pyttsx3.init()
for page_num in range(pdfreader.numPages):   
    text = pdfreader.getPage(page_num).extractText()  ## extracting text from the PDF
    cleaned_text = text.strip().replace('\n',' ')  ## Removes unnecessary spaces and break lines
    print(cleaned_text)                ## Print the text from PDF
    #speaker.say(cleaned_text)        ## Let The Speaker Speak The Text
    speaker.save_to_file(cleaned_text,'story.mp3')  ## Saving Text In a audio file 'story.mp3'
    speaker.runAndWait()
speaker.stop()

2. Play random music from the list

This script will randomly select a song from the song folder to play. It should be noted that os.startfile only supports Windows systems.

import random, os
music_dir = 'G:\\new english songs'
songs = os.listdir(music_dir)
song = random.randint(0,len(songs))
print(songs[song])  ## Prints The Song Name
os.startfile(os.path.join(music_dir, songs[0])) 

3. There are no more bookmarks

Before going to bed every day, I will search for some good content on the Internet and read it the next day. Most of the time, I bookmark the websites or articles I encounter, but my bookmarks are increasing every day, so that now there are more than 100 bookmarks around my browser. Therefore, with the help of python, I came up with another way to solve this problem. Now, I copy and paste the links of these websites into a text file. Every morning, I run the script and open all these websites again in my browser.

import webbrowser
with open('./websites.txt') as reader:
    for link in reader:
        webbrowser.open(link.strip())

The code uses the webbrowser, a library in Python that can automatically open the URL in the default browser.

4. Intelligent weather information

The website of the National Meteorological Administration provides an API for obtaining weather forecasts and directly returns weather data in json format. So you just need to get the corresponding field from json.

The following is the weather website of the specified city (county, district). Directly open the website and the weather data of the corresponding city will be returned. For example:

http://www.weather.com.cn/data/cityinfo/101021200.html the corresponding weather website of Xuhui District, Shanghai.

The specific codes are as follows:

import requests
import json
import logging as log

def get_weather_wind(url):
    r = requests.get(url)
    if r.status_code != 200:
        log.error("Can't get weather data!")
    info = json.loads(r.content.decode())

    # get wind data
    data = info['weatherinfo']
    WD = data['WD']
    WS = data['WS']
    return "{}({})".format(WD, WS)


def get_weather_city(url):
    # open url and get return data
    r = requests.get(url)
    if r.status_code != 200:
        log.error("Can't get weather data!")

    # convert string to json
    info = json.loads(r.content.decode())

    # get useful data
    data = info['weatherinfo']
    city = data['city']
    temp1 = data['temp1']
    temp2 = data['temp2']
    weather = data['weather']
    return "{} {} {}~{}".format(city, weather, temp1, temp2)


if __name__ == '__main__':
    msg = """**Weather reminder**:  

{} {}  
{} {}  

source: National Meteorological Administration
""".format(
    get_weather_city('http://www.weather.com.cn/data/cityinfo/101021200.html'),
    get_weather_wind('http://www.weather.com.cn/data/sk/101021200.html'),
    get_weather_city('http://www.weather.com.cn/data/cityinfo/101020900.html'),
    get_weather_wind('http://www.weather.com.cn/data/sk/101020900.html')
)
    print(msg)

The operation results are as follows:

5. Long URL becomes short URL

Sometimes, those big URLs become very annoying and difficult to read and share. This foot can change the long URL into a short URL.

import contextlib
from urllib.parse import urlencode
from urllib.request import urlopen
import sys

def make_tiny(url):
 request_url = ('http://tinyurl.com/api-create.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()

This script is very practical. For example, if the content platform is to block official account, then the link of official account can be changed into short link and inserted into it, and then we can bypass it.

6. Clean up download folders

One of the most chaotic things in the world is the developer's download folder, which contains a lot of disorderly files. This script will clean up your download folder according to the size limit and clean up older files:

import os
import threading
import time
 
 
def get_file_list(file_path):
#Files are sorted by last modification time
    dir_list = os.listdir(file_path)
    if not dir_list:
        return
    else:
        dir_list = sorted(dir_list, key=lambda x: os.path.getmtime(os.path.join(file_path, x)))
    return dir_list
 
def get_size(file_path):
    """[summary]
    Args:
        file_path ([type]): [catalogue]

    Returns:
        [type]: Returns the size of the directory, MB
    """
    totalsize=0
    for filename in os.listdir(file_path):
        totalsize=totalsize+os.path.getsize(os.path.join(file_path, filename))
    #print(totalsize / 1024 / 1024)
    return totalsize / 1024 / 1024
 
def detect_file_size(file_path, size_Max, size_Del):
    """[summary]
    Args:
        file_path ([type]): [File directory]
        size_Max ([type]): [Maximum folder size]
        size_Del ([type]): [exceed size_Max Size to delete when]
    """
    print(get_size(file_path))
    if get_size(file_path) > size_Max:
        fileList = get_file_list(file_path)
        for i in range(len(fileList)):
            if get_size(file_path) > (size_Max - size_Del):
                print ("del :%d %s" % (i + 1, fileList[i]))
                #os.remove(file_path + fileList[i])
    
 
def detectFileSize():
 #Detect threads every 5 seconds
    while True:
        print('======detect============')
        detect_file_size("/Users/aaron/Downloads/", 100, 30)
        time.sleep(5)
  
if __name__ == "__main__":
    #Create detection thread
    detect_thread = threading.Thread(target = detectFileSize)
    detect_thread.start()

Posted on Fri, 03 Dec 2021 13:30:48 -0500 by ScOrPi