解决日常问题的 10 个 Python 自动化脚本
用阅读来解决日常生活问题,如解决问题的绘本 #生活技巧# #家庭教育建议# #阅读推广方法#
作为程序员,我们经常手动执行可以自动化的任务。考虑一下您每天执行的任务,例如检查电子邮件、编辑图像或处理 PDF。在本文中,我们介绍了10 个可以简化您日常生活的自动化脚本。请务必为本文添加书签,然后我们就可以开始了。
图片编辑器
需要 Mini Photoshop 来使用 Python 以编程方式编辑图片吗?然后是使用Wand 模块的自动化脚本,该模块是流行图像处理软件ImageMagick 的包装器。
该脚本提供了多种功能,例如调整大小、压缩、裁剪、翻转、旋转等。轻松为您的照片增添专业气息。
# Pitcher Editor # pip install Wand from wand.image import Image # load the pic pic = Image(filename='pic.png') # resize pics pic.resize(200, 200) # crop pics pic.crop(0, 0, 100, 100) # flip pics pic.flip() # rotate pics pic.rotate(90) # compress pics pic.compression_quality = 99 # blur pics pic.blur() # sharpen pics pic.sharpen() # combine pics pic2 = Image(filename='pic2.png') pic.sequence.append(pic2) # compare pics result = pic.compare(pic2) # GreyScale Pic pic.type = 'grayscale' # Transpose Pic pic.transpose() # save pics pic.save(filename='pic3.png')
123456789101112131415161718192021222324252627282930 自动发送电子邮件
使用这个很棒的自动化脚本,它可以帮助您以编程方式向任何人发送电子邮件。该脚本使用Smtplib 和电子邮件模块,帮助您将电子邮件发送到任何邮件服务器,如Gmail、Outlook 等。
查看下面的代码示例,了解发送简单电子邮件和带有附件(例如文件和照片)的电子邮件。
# Automating Email Sending import smtplib as smtp from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders def Send_Email(email, pwd, to, subject, body): msg = MIMEMultipart() msg['From'] = email msg['To'] = to msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) server = smtp.SMTP('smtp.gmail.com', 587) server.starttls() server.login(email, pwd) text = msg.as_string() server.sendmail(email, to, text) server.quit() print('Email Sent') def Send_Email_With_Attachment(email, pwd, to, subject, body, file): # send email with attachment msg = MIMEMultipart() msg['From'] = email msg['To'] = to msg['Subject'] = subject msg.attach(MIMEText(body, 'plain')) server = smtp.SMTP('smtp.gmail.com', 587) server.starttls() server.login(email, pwd) text = msg.as_string() attachment = open(filename, 'rb') part = MIMEBase('application', 'octet-stream') part.set_payload(attachment.read()) attachment.close() encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename= ' + file) msg.attach(part) server.sendmail(email, to, text) server.quit() print('Email Sent')
1234567891011121314151617181920212223242526272829303132333435363738394041' PDF 文本提取器
需要从 PDF 的多个页面中获取文本,那么这里是适合您的自动化脚本,它使用 PyMuPDF 模块,该模块可让您从任何 PDF 文件的单个、多个或特定页面中获取文本。
如果您有大量 PDF 文件需要提取,或者您需要 PDF 项目方面的帮助,那么这个方便的工具尤其有用。
PDF 文本提取器
# PDF Text Extractor # pip install PyMuPDF import fitz as pdfExtract def Text_Extractor(pdfFile): # Open the PDF file pdf_doc = pdfExtract.open(pdfFile) # Get the total number of pages in the PDF pages = pdf_doc.page_count # Extract text from each page for page_no in range(pages): page = pdf_doc.load_page(page_no) text = page.get_text() print(f"Page {page_no + 1}:\n{text}\n") Text_Extractor("sample.pdf") 1234567891011121314
Excel 编辑器
使用此自动化脚本通过 Python读取、写入或编辑Excel 文件。该脚本使用Openpyxl 模块,该模块可以帮助您自动化数据输入、Excel 写入等过程。它是简化工作流程的便捷工具。
# Excel Editor # pip install openpyxl import openpyxl as excel from openpyxl.styles import Font # load Excel File wbook = excel.load_workbook('test.xlsx') ws = wbook.active # read all data for row in ws.rows: for cell in row: print(cell.value, end=' ') print() # read data by cell print(ws['A1'].value) # read data by row for row in ws.rows: print(row[0].value, row[1].value, row[2].value) # read data by column for col in ws.columns: print(col[0].value, col[1].value, col[2].value) # write data wbook = excel.Workbook() ws = wbook.active # write data ws['A1'] = 'Hello' # write data to specific cell ws.cell(row=1, column=2).value = 'World' # append data ws.append(['Python', 'is', 'good']) # change font ws['A1'].font = Font(size=20, color='FF0000') # change column width ws.column_dimensions['A'].width = 30 # change row height ws.row_dimensions[1].height = 50 # Delete row ws.delete_rows(1) # Delete column ws.delete_cols(1) # Delete Cell ws['A1'] = '' # Save Excel File wbook.save('test.xlsx')
12345678910111213141516171819202122232425262728293031323334353637383940414243 拼写检查器
使用此使用 Pyspellchecker 模块的 Python 脚本以编程方式自动执行拼写检查任务。它会扫描您的文本中是否存在拼写错误的单词并提供更正。该脚本还可用于扫描整个文本段落。
# Spelling Checker # pip install pyspellchecker from spellchecker import SpellChecker def spell_check_word(word): # Create a SpellChecker instance speller = SpellChecker() # Generate suggestions for the misspelled word corrections = speller.candidates(word) print("Correction: ", corrections) spell_check_word('mussage') 12345678910
语音转文本人工智能
如果您希望将实时语音转换为文本,那么这里是使用SpeechRecognition 模块的 Python 脚本,该模块将访问麦克风并识别您的语音,然后使用第二个模块Pocketsphinx将其转换为文本格式。查看下面的示例代码。
# Voice to Text # pip install SpeechRecognition # pip install pocketsphinx import speech_recognition as sr def Voice_To_Text(): recognizer = sr.Recognizer() # Use the default microphone as the audio source with sr.Microphone() as source: print("Say something...") audio = recognizer.listen(source) # recognize speech using Sphinx text_result = recognizer.recognize_sphinx(audio) return text_result if __name__ == "__main__": output = Voice_To_Text() if output: print("Transcribed Text:") print(output)
123456789101112131415161718 创建 Restful API
现在,您可以使用此 Python 脚本轻松创建自己的 API,该脚本使用FastApi 模块,您现在可以快速、轻松地创建自己的 API。Fastapi简单易懂的代码结构是我个人的最爱,使其成为只需几行代码即可设置 API 的优秀工具。
# Build RestApi # pip install fastapi # pip install uvicorn from fastapi import FastAPI import uvicorn app = FastAPI() @app.get("/add/{a}/{b}") def add(a: int, b: int): return {"message": a + b} @app.get("/subtract/{a}/{b}") def subtract(a: int, b: int): return {"message": a - b} @app.get("/multiply/{a}/{b}") def multiply(a: int, b: int): return {"message": a * b} @app.get("/divide/{a}/{b}") def divide(a: int, b: int): return {"message": a / b} # Run RestApi if __name__ == "__main__": uvicorn.run(app, host="localhost", port=8000)
123456789101112131415161718192021 获取最新消息
使用此 Python 脚本轻松自动更新每日新闻。通过使用Requests 和 BeautifulSoup模块,您可以轻松地从 BBC 网站获取最新的新闻标题和摘要。轻松掌握最新信息。查看下面的代码。
# Fetch Daily News # pip install requests # pip install bs4 import requests from bs4 import BeautifulSoup def fetch_news(): url = 'https://www.bbc.com/news' # Send an HTTP GET request to the BBC News website r = requests.get(url) # Parse the HTML content using BeautifulSoup soup = BeautifulSoup(r.content, 'html.parser') # Select article elements from the HTML using CSS class selector articles = soup.select('.gs-c-promo-body') # Iterate over the selected article elements and extract info for idx, article in enumerate(articles, 1): try: # Extract the title and summary of the article title = article.select_one('.gs-c-promo-heading__title').text.strip() summary = article.select_one('.gs-c-promo-summary').text.strip() # Print the title and summary of the article print(f"{idx}. {title}\n {summary}\n") except: pass if __name__ == '__main__': fetch_news()
123456789101112131415161718192021222324252627282930Python 截图
此 Python 脚本可以帮助您以编程方式自动执行屏幕截图。通过下面提供的使用 Pyautogui 模块的代码,可以毫不费力地捕获屏幕截图。
# Py Screenshot # pip install pyautogui import pyautogui def Screenshot(): img = pyautogui.screenshot() img.save("screenshot.png") Screenshot() 12345678
自动化桌面应用程序
想要像自动化网站一样自动化您的桌面应用程序,那么这里是另一个使用Pynput 模块的Python 脚本,它可以让您以编程方式控制鼠标和键盘操作。
# Automate Desktop Apps # pip install pynput from pynput.keyboard import Key, Controller from pynput.mouse import Button, Controller keyboard = Controller() # type keyboard.type('Hello World') # press key keyboard.press(Key.space) # release key keyboard.release(Key.space) # press combination keyboard.press(Key.cmd) keyboard.press('r') keyboard.release('r') keyboard.release(Key.cmd) # Press function keys keyboard.press(Key.f1) # Get Pressed Key with keyboard.pressed(Key.shift): keyboard.press('a') keyboard.release('a') # Get Mouse Position mouse = Controller() print(mouse.position) # Set Mouse Position mouse.position = (10, 20) # move mouse mouse.move(5, -5) # Left Click mouse.click(Button.left, 1) # Right Click mouse.click(Button.right, 1) # Scroll mouse.scroll(0, 2) # Drag mouse.press(Button.left) # Release mouse.release(Button.left) # Double Click mouse.click(Button.left, 2)
1234567891011121314151617181920212223242526272829303132333435363738394041网址:解决日常问题的 10 个 Python 自动化脚本 https://www.yuejiaxmz.com/news/view/155985
相关内容
10 个 Python 脚本来自动化你的日常任务10个Python脚本来自动化你的日常任务
十个Python脚本,轻松实现日常任务自动化
掌握Python,高效生活:揭秘5个实用脚本,轻松解决日常编程难题!
AppTask: 使用Python实现日常APP任务自动化
让生活自动化的5个Python项目:从初级到高级
5 个自动化生活的 Python 项目:从初学者到高级
10个非常规方法,来解决日常问题!
高效Python工作流自动化:简化开发流程的最佳实践
Python RPA 流程自动化快速上手