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个方便好用的 Python 自动化脚本,拿来即用!

相比大家都听过自动化生产线、自动化办公等词汇,在没有人工干预的情况下,机器可以自己完成各项任务,这大大提升了工作效率。
编程世界里有各种各样的自动化脚本,来完成不同的任务。

尤其 Python 非常适合编写自动化脚本,因为它语法简洁易懂,而且有丰富的第三方工具库。

这次我们使用 Python 来实现几个自动化场景,或许可以用到你的工作中。

1、自动化阅读网页新闻
这个脚本能够实现从网页中抓取文本,然后自动化语音朗读,当你想听新闻的时候,这是个不错的选择。

代码分为两大部分,第一通过爬虫抓取网页文本呢,第二通过阅读工具来朗读文本。

需要的第三方库:

Beautiful Soup - 经典的 HTML/XML 文本解析器,用来提取爬下来的网页信息

requests - 好用到逆天的 HTTP 工具,用来向网页发送请求获取数据

Pyttsx3 - 将文本转换为语音,并控制速率、频率和语音

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 a audio file
engine.runAndWait()

2、自动生成素描草图
这个脚本可以把彩色图片转化为铅笔素描草图,对人像、景色都有很好的效果。

而且只需几行代码就可以一键生成,适合批量操作,非常的快捷。

需要的第三方库:

Opencv - 计算机视觉工具,可以实现多元化的图像视频处理,有 Python 接口

""" 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)

image
3、自动发送多封邮件
这个脚本可以帮助我们批量定时发送邮件,邮件内容、附件也可以自定义调整,非常的实用。

相比较邮件客户端,Python 脚本的优点在于可以智能、批量、高定制化地部署邮件服务。

需要的第三方库:

Email - 用于管理电子邮件消息

Smtlib - 向 SMTP 服务器发送电子邮件,它定义了一个 SMTP 客户端会话对象,该对象可将邮件发送到互联网上任何带有 SMTP 或 ESMTP 监听程序的计算机

Pandas - 用于数据分析清洗地工具

import smtplib 
from email.message import EmailMessage
import pandas as pd

def 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]","delta@371") ## login id and password of gmail
        smtp.send_message(email)                    ## Sending email
        print("email send 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)

4、自动化数据探索
数据探索是数据科学项目的第一步,你需要了解数据的基本信息才能进一步分析更深的价值。

一般我们会用 pandas、matplotlib 等工具来探索数据,但需要自己编写大量代码,如果想提高效率,Dtale 是个不错的选择。

Dtale 特点是用一行代码生成自动化分析报告,它结合了 Flask 后端和 React 前端,为我们提供了一种查看和分析 Pandas 数据结构的简便方法。

我们可以在 Jupyter 上实用 Dtale。

需要的第三方库:

Dtale - 自动生成分析报告

### 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)

image
5、自动桌面提示
这个脚本会自动触发 windows 桌面通知,提示重要事项,比如说:您已工作两小时,该休息了

我们可以设定固定时间提示,比如隔 10 分钟、1 小时等

用到的第三方库:

win10toast - 用于发送桌面通知的工具

from win10toast import ToastNotifier
import time
toaster = 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 * 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)

image

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。