banner
andrewji8

Being towards death

Heed not to the tree-rustling and leaf-lashing rain, Why not stroll along, whistle and sing under its rein. Lighter and better suited than horses are straw sandals and a bamboo staff, Who's afraid? A palm-leaf plaited cape provides enough to misty weather in life sustain. A thorny spring breeze sobers up the spirit, I feel a slight chill, The setting sun over the mountain offers greetings still. Looking back over the bleak passage survived, The return in time Shall not be affected by windswept rain or shine.
telegram
twitter
github

5 convenient and easy-to-use Python automation scripts, ready to use!

Compared to terms like automated production lines and automated offices that everyone has heard of, machines can complete tasks on their own without human intervention, greatly improving work efficiency.

There are various automation scripts in the programming world to accomplish different tasks.

Python is especially suitable for writing automation scripts because of its concise and understandable syntax, as well as its rich third-party tool libraries.

This time, we use Python to implement several automation scenarios that may be useful in your work.

  1. Automated reading of web news
    This script can extract text from web pages and automatically read it aloud. It's a good choice when you want to listen to the news.

The code is divided into two parts: the first part uses web scraping to extract web page text, and the second part uses a reading tool to read the text.

Required third-party libraries:

  • Beautiful Soup: a classic HTML/XML text parser used to extract information from web pages that have been crawled.
  • Requests: a powerful HTTP tool used to send requests to web pages and retrieve data.
  • Pyttsx3: converts text to speech and controls the rate, frequency, and voice.
import pyttsx3
import requests
from bs4 import BeautifulSoup

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
newVoiceRate = 130  # Reduce the speech rate
engine.setProperty('rate', newVoiceRate)
engine.setProperty('voice', voices[1].id)

def speak(audio):
    engine.say(audio)
    engine.runAndWait()

text = str(input("Paste article\n"))
res = requests.get(text)
soup = BeautifulSoup(res.text, 'html.parser')

articles = []
for i in range(len(soup.select('.p'))):
    article = soup.select('.p')[i].getText().strip()
    articles.append(article)

text = " ".join(articles)
speak(text)
# engine.save_to_file(text, 'test.mp3')  # If you want to save the speech as an audio file
engine.runAndWait()
  1. Automatic generation of sketch drawings
    This script can convert color images into pencil sketch drawings, which have good effects on portraits and scenery.

And it only takes a few lines of code to generate them with one click, making it suitable for batch operations and very convenient.

Required third-party libraries:

  • OpenCV: a computer vision tool that can achieve diversified image and video processing with a Python interface.
""" Photo Sketching Using Python """
import cv2

img = cv2.imread("elon.jpg")

## Image to Gray Image
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

## Gray Image to Inverted Gray Image
inverted_gray_image = 255 - gray_image

## Blurring The Inverted Gray Image
blurred_inverted_gray_image = cv2.GaussianBlur(inverted_gray_image, (19, 19), 0)

## Inverting the blurred image
inverted_blurred_image = 255 - blurred_inverted_gray_image

### Preparing Photo sketching
sketck = cv2.divide(gray_image, inverted_blurred_image, scale=256.0)

cv2.imshow("Original Image", img)
cv2.imshow("Pencil Sketch", sketck)
cv2.waitKey(0)
  1. Automatic sending of multiple emails
    This script can help us send emails in batches at scheduled times, and the content and attachments of the emails can be customized, which is very practical.

Compared to email clients, the advantage of Python scripts is that they can deploy email services intelligently, in batches, and with high customization.

Required third-party libraries:

  • Email: used to manage email messages.
  • Smtplib: sends email to an SMTP server. It defines an SMTP client session object that can send emails to any computer with an SMTP or ESMTP listener.
  • Pandas: a tool for data analysis and cleaning.
import smtplib
from email.message import EmailMessage
import pandas as pd

def send_email(remail, rsubject, rcontent):
    email = EmailMessage()  # Creating an object for EmailMessage
    email['from'] = 'The Pythoneer Here'  # Person who is sending
    email['to'] = remail  # Whom we are sending
    email['subject'] = rsubject  # Subject of email
    email.set_content(rcontent)  # Content of email
    with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp:
        smtp.ehlo()  # Server object
        smtp.starttls()  # Used to send data between server and client
        smtp.login("[email protected]", "delta@371")  # Login ID and password of Gmail
        smtp.send_message(email)  # Sending email
        print("Email sent to", remail)  # Printing success message

if __name__ == '__main__':
    df = pd.read_excel('list.xlsx')
    length = len(df) + 1

    for index, item in df.iterrows():
        email = item[0]
        subject = item[1]
        content = item[2]

        send_email(email, subject, content)
  1. Automated data exploration
    Data exploration is the first step in data science projects. You need to understand the basic information of the data before further analyzing its deeper value.

Usually, we use tools like pandas and matplotlib to explore data, but we need to write a lot of code ourselves. If we want to improve efficiency, Dtale is a good choice.

The feature of Dtale is that it generates automated analysis reports with just one line of code. It combines Flask backend and React frontend to provide us with a convenient way to view and analyze Pandas data structures.

We can use Dtale in Jupyter.

Required third-party libraries:

  • Dtale: generates analysis reports automatically.
### Importing Seaborn Library For Some Datasets
import seaborn as sns

### Printing Inbuilt Datasets of Seaborn Library
print(sns.get_dataset_names())

### Loading Titanic Dataset
df = sns.load_dataset('titanic')

### Importing The Library
import dtale

#### Generating Quick Summary
dtale.show(df)
  1. Automatic desktop notifications
    This script will automatically trigger Windows desktop notifications to remind you of important matters, such as "You have been working for two hours, it's time to take a break."

We can set fixed time intervals for reminders, such as every 10 minutes or every hour.

Required third-party libraries:

  • win10toast: a tool for sending desktop notifications.
from win10toast import ToastNotifier
import time

toaster = ToastNotifier()

header = input("What do you want me to remember?\n")
text = input("Related message\n")
time_min = float(input("In how many minutes?\n"))

time_min = time_min * 60
print("Setting up reminder...")
time.sleep(2)
print("All set!")
time.sleep(time_min)
toaster.show_toast(f"{header}", f"{text}", duration=10, threaded=True)
while toaster.notification_active():
    time.sleep(0.005)
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.