程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

How fragrant! Five easy-to-use Python automation scripts

編輯:Python

Compared with everyone who has heard of automatic production line 、 Office automation and other words , Without human intervention , The machine can complete all tasks by itself , This greatly improves work efficiency .

There are all kinds of automated scripts in the programming world , To accomplish different tasks .

especially Python Very suitable for writing automated scripts , Because its grammar is simple and easy to understand , And there are rich third-party tool Libraries .

This time we use Python To implement several automation scenarios , Maybe it can be used in your work .

1、 Automatically read web news

This script can grab text from web pages , Then automatic voice reading , When you want to hear the news , It's a good choice .

The code is divided into two parts , First, grab the web text through the crawler , Second, read the text through reading tools .

Third party libraries needed :

Beautiful Soup - classical HTML/XML Text parser , Used to extract the information of the web page climbing down

requests - Good to use against the sky HTTP Tools , Used to send requests to web pages to get data

Pyttsx3 - Convert text to speech , And control the rate 、 Frequency and voice

import pyttsx3import requestsfrom bs4 import BeautifulSoupengine = pyttsx3.init('sapi5')voices = engine.getProperty('voices')newVoiceRate = 130                       ## Reduce The Speech Rateengine.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 a audio fileengine.runAndWait()

2、 Automatically generate sketch

This script can convert color pictures into pencil sketches , To the portrait 、 The scenery has a good effect .

And it only takes a few lines of code to generate , Suitable for batch operation , Very fast .

Third party libraries needed :

Opencv - Computer vision tools , It can realize diversified image and video processing , Yes 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)

3、 Automatically send multiple emails

This script can help us send emails in batches and on a regular basis , Email content 、 Attachments can also be customized , Very practical .

Compared with the mail client ,Python The advantage of scripts is that they can intelligently 、 Batch 、 Highly customized deployment of mail services .

Third party libraries needed :

Email - Used to manage email messages

Smtlib - towards SMTP The server sends email , It defines a SMTP Client session object , This object can send mail to any on the Internet SMTP or ESMTP The computer listening to the program

Pandas - Tools for data analysis and cleaning

import smtplib from email.message import EmailMessageimport pandas as pddef send_email(remail, rsubject, rcontent):    email = EmailMessage()                          ## Creating a 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]","[email protected]") ## login id and password of gmail        smtp.send_message(email)                    ## Sending email        print("email send to ",remail)              ## Printing success messageif __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)

4、 Automated data exploration

Data exploration is the first step of the data science project , You need to understand the basic information of the data to further analyze the deeper value .

We usually use pandas、matplotlib And other tools to explore data , But you need to write a lot of code yourself , If you want to be more efficient ,Dtale It's a good choice .

Dtale The feature is to generate automatic analysis report with one line of code , It is a combination of Flask Back end and React front end , It provides us with a way to view and analyze Pandas A simple method of data structure .

We can do it in Jupyter Practical Dtale.

Third party libraries needed :

Dtale - Automatically generate analysis report

### Importing Seaborn Library For Some Datasetsimport seaborn as sns### Printing Inbuilt Datasets of Seaborn Libraryprint(sns.get_dataset_names())### Loading Titanic Datasetdf=sns.load_dataset('titanic')### Importing The Libraryimport dtale#### Generating Quick Summarydtale.show(df)

5、 Automatic desktop prompt

This script will automatically trigger windows Desktop notification , Prompt important matters , for instance : You have been working for two hours , It's time to rest

We can set a fixed time prompt , Such as septum 10 minute 、1 Hours, etc

Third party libraries used :

win10toast - Tools for sending desktop notifications

from win10toast import ToastNotifierimport timetoaster = ToastNotifier()header = input("What You Want Me To Remember\n")text = input("Releated Message\n")time_min=float(input("In how many minutes?\n"))time_min = time_min * 60print("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)     

Summary

Python The automation functions that can be realized are very rich , If you can “ lazy ” You might as well try the demand scenario .


Reference resources :

https://medium.com/pythoneers/10-handy-automation-scripts-you-should-try-using-python-fc9450116938

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved