十個Python自動化腳本,提高辦公效率
今年人工智能在各個領域蓬勃發展,因此我們也必須將日常重復且耗時的手動任務轉變為自動化。這篇文章將向你展示10個Python腳本,可用于實現工作的自動化。將這篇文章列入你的閱讀清單,讓我們開始吧。
目錄
- 人工智能聊天機器人
- 制作網頁應用程序
- 將PDF轉換為Excel
- 制作通知器
- 神奇照片編輯器
- 制作校對工具
- 簡單圖像下載器
- URL短鏈接生成器
- 隱藏CSV模塊
- 獲取臨時郵箱
1. 人工智能聊天機器人
如果你想要一個免費AI聊天機器人,比如ChatGPT,可以使用這個Python 腳本,它利用了Gemini(谷歌AI),這是AI市場上最熱門且智能的工具之一。Gemini為Pro版本提供每分鐘60次請求的免費API訪問。
下面介紹如何使用Gemini創建你自己的AI聊天機器人,并與之聊天、生成文本、提問或分析照片等等。歡迎復制下面的代碼。
# 聊天機器人 AI
# pip install google-generativeai
# pip install pillow
import google.generativeai as genai
from PIL import Image
# 設置 API 密鑰
genai.configure(api_key='YOUR API KEY')
# 生成文本
model = genai.GenerativeModel('gemini-pro')
response = model.generate_content("給我一些有趣的周末計劃列表")
print(response.text)
# 與 AI 聊天
chat = model.start_chat()
chat.send_message("Python 和 JavaScript 哪個更好?")
for m in chat.history:
print(m.parts[0].text)
# 分析圖像
model = genai.GenerativeModel('gemini-pro-vision')
img = Image.open('street.jpg')
response = model.generate_content(img)
print(response.text)
# 帶文本分析圖像
img = Image.open('NewYork_Street.jpg')
response = model.generate_content(["請告訴我確切位置", img])
print(response.text)
2. 制作網絡應用程序
現在不需要HTML、CSS和JS,就可以通過Streamlit使用幾行代碼創建一個漂亮的網頁應用。這個Python模塊非常易用于照片編輯器、聊天機器人、作品集、圖標生成器和圖像生成器等網頁應用。一定要試試下面的腳本。
可查看Streamlit應用庫,看看其他開發者制作了什么。??
# pip install streamlit
# import streamlit as st
def calculate(operation, num1, num2):
if operation == '加':
return num1 + num2
elif operation == '減':
return num1 - num2
elif operation == '乘':
return num1 * num2
elif operation == '除':
if num2 == 0:
return "不能除以零"
return num1 / num2
# Streamlit 應用
def webapp():
st.title("簡單計算器")
num1 = st.number_input("輸入第一個數字", value=0.0, format="%f")
num2 = st.number_input("輸入第二個數字", value=0.0, format="%f")
operation = st.selectbox("選擇操作",
["加", "減", "乘", "除"])
if st.button("計算"):
result = calculate(operation, num1, num2)
st.write(f"結果是: {result}")
webapp()
3. 將PDF轉換為Excel
厭倦了從PDF復制表格和數據到Excel?那么使用下面的Python腳本將其自動化,它使用Openpyxl、Tabula和Pandas模塊。Tabula是一個流行的模塊,可以將任何類型的表格數據提取到CSV、Excel,甚至JSON。歡迎隨意復制下面的代碼。??
# PDF 轉 Excel
# pip install tabula-py
# pip install pandas
# pip install openpyxl
import tabula
import pandas as pd
# 讀取 PDF 文件
filename = "myPDF.pdf"
# 將 PDF 轉換為 Excel
df = tabula.read_pdf(filename, pages='all', multiple_tables=True)
# 保存 Excel
writer = pd.ExcelWriter('output.xlsx')
for i, table in enumerate(df):
table.to_excel(writer, sheet_name=f'Sheet{i}', index=False)
writer.save()
print("PDF 轉 Excel 轉換完成!")
4. 制作通知器
你知道你可以制作自己想要的通知器嗎?比如水分提醒通知器、雨天通知器,或者你最喜歡的產品打折通知器等等?下面的腳本制作了一個電池通知器,使用Plyer模塊在任務欄提醒電池是否充滿或降到特定百分比。
現在就制作你自己的通知器吧??,如果有任何反饋請告訴我。
# 電池通知器
# pip install plyer
import psutil
from plyer import notification
import time
def getBatteryStatus():
battery = psutil.sensors_battery()
percent = battery.percent
return percent
def Notifier(percent):
if percent >= 80:
notification.notify(
title="電池充滿",
message="請拔掉充電器",
timeout=10
)
elif percent <= 30:
notification.notify(
title="電池低電",
message="請插上充電器",
timeout=10
)
if __name__ == "__main__":
while True:
percent = getBatteryStatus()
Notifier(percent)
time.sleep(60)
5. 神奇照片編輯器
如果你不想使用Photoshop進行小幅度的照片編輯,可使用下面的自動化腳本,它可以調整大小、模糊、翻轉、裁剪、添加陰影和壓縮等等。下面的代碼使用了流行的Pillow模塊,專門用于圖像處理。使用Pillow可進行批量圖像編輯,比如合并多張照片或調整大小和裁剪。
# Magic Photo Editor
# pip install pillow
from PIL import Image, ImageFilter
import os
def ResizeImage(image, size):
image.resize(size, Image.ANTIALIAS)
image.save("resized.jpg")
def RotateImage(image, angle):
image.rotate(angle)
image.save("rotated.jpg")
def CropImage(image, box):
image.crop(box)
image.save("cropped.jpg")
def FlipImage(image):
image.transpose(Image.FLIP_LEFT_RIGHT)
image.save("flipped.jpg")
def CompressImage(image, quality):
image.save("compressed.jpg", quality=quality)
def BlurImage(image, radius):
image.filter(ImageFilter.GaussianBlur(radius))
image.save("blurred.jpg")
def GreyScaleImage(image):
image.convert("L")
image.save("greyscale.jpg")
def ConvertFormat(image, format):
image.save("converted." + format, format)
def Add_Shadow(image, offset, background_color):
image.filter(ImageFilter.BoxBlur(offset))
image.save("shadow.jpg")
def SharpenImage(image, factor):
image.filter(ImageFilter.SHARPEN)
image.save("sharpened.jpg")
if __name__ == "__main__":
image = Image.open("photo.jpg")
ResizeImage(image, (100, 100))
RotateImage(image, 90)
CropImage(image, (0, 0, 100, 100))
FlipImage(image)
CompressImage(image, 50)
BlurImage(image, 10)
GreyScaleImage(image)
ConvertFormat(image, "png")
Add_Shadow(image, 10, "black")
SharpenImage(image, 2)
6. 制作校對工具
你可以使用Python制作自己的校對軟件。這個自動化腳本使用Language_tool模塊,這是一個LanguageTool語法檢查網站的封裝。這個模塊非常適合修正文本的語法錯誤和拼寫錯誤。當你有長文本或多個文本或文檔文件需要校對時,它非常方便。
# pip install language-tool-python
# 校對工具
import language_tool_python
# 設置語言
tool = language_tool_python.LanguageTool('en-US')
# 校對文本
text = 'The smill of fliwers is good'
matches = tool.check(text)
# 獲取錯誤
for mistake in matches:
print(mistake)
# 更正文本
correction = tool.correct(text)
print(correction)
7. 簡單圖像下載器
需要一個腳本來節省你尋找和下載圖像的時間嗎?這個自動化腳本使用Simple_image_download模塊,讓你可以輕松下載100張圖像,任何關鍵字都可以。
# 自動照片下載器
# pip install simple_image_download
from simple_image_download import simple_image_download
def Download_Images(keyword, no_of_images = 1):
simp = simple_image_download.Downloader()
simp.download(keyword, no_of_images)
print("圖像已下載")
if __name__ == "__main__":
Download_Images("貓")
8. URL 短鏈接生成器
如果有大量需要縮短的鏈接和URL,可以使用下面的自動化腳本編程,該腳本使用Pyshorteners模塊,它使用TinyURL開源API將您的URL轉換為可與任何人共享的短網址。
# URL 短鏈接生成器
# pip install pyshorteners
import pyshorteners
def Shortner(Link):
req = pyshorteners.Shortener()
short = req.tinyurl.short(Link)
print("縮短的 URL: ", short)
return short
if __name__ == "__main__":
Link = input("輸入 URL: ")
Shortner(Link)
9. 隱藏CSV模塊
不想使用Pandas讀取和寫入CSV?沒關系,使用Python內置的最快CSV模塊,它可讓你讀取、寫入和追加CSV數據。下面附上可直接使用的示例代碼。
import csv
# 讀取 CSV 文件
filename = "test.csv"
with open(filename, 'r') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
print(row)
# 追加到 CSV 文件
rows = [['John', '作者', '1', '9.5']]
with open(filename, 'a') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerows(rows)
# 寫入 CSV 文件
fields = ['姓名', '專業', '年級', 'CGPA']
rows = [['Haider', '作家', '3', '9.3']]
filename = "test.csv"
with open(filename, 'w') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(fields)
csvwriter.writerows(rows)
10. 獲取臨時郵箱
如果你想要找一個需要登錄的網站,但出于安全考慮,你不想提供自己的郵箱地址,因為害怕收到促銷信息和被跟蹤。這種情況下就可以使用下面的Python 腳本為你生成一個臨時郵箱,用于注冊網站。
# 獲取臨時郵箱
# pip install tempmail-lol
from TempMail import TempMail
mail = TempMail()
# 登錄你的臨時郵箱
inb = TempMail("輸入 24 位 ID", "輸入 32 或 36 位 Token")
# 創建新的臨時郵箱
email = TempMail.generateInbox(mail)
print(email)
# 檢查郵件
inb = TempMail.getEmails(mail, inbox=email)
print(inb)
總結
這些Python腳本展現了Python在自動化日常任務上的多功能性。將它們融入你的工作流程,可以提升效率、節省時間,并減輕重復勞動的壓力。不妨探索這些自動化腳本,看看Python如何簡化你的生活。