数据分析1480 | 汇总17个工作必备的Python自动化代码(下)建议收藏!

本文来源公众号**"数据分析1480"**,仅用于学术分享,侵权删,干货满满。

原文链接:汇总17个工作必备的Python自动化代码

您是否厌倦了在日常工作中做那些重复性的任务?简单但多功能的Python脚本可以解决您的问题。

我们将通过上下两个篇章为您介绍17个能够自动执行各种任务并提高工作效率Python脚本及其代码。无论您是开发人员、数据分析师,还是只是希望简化工作流程的人,这些脚本都能满足您的需求。

之前的9个案例看上一篇文章数据分析1480 | 汇总17个工作必备的Python自动化代码(上)-CSDN博客

10.网络自动化

10.1检查网站状态​​

python 复制代码
```
# Python script to check the status of a website
import requests
def check_website_status(url):
    response = requests.get(url)
    if response.status_code == 200:
        # Your code here to handle a successful response
    else:
        # Your code here to handle an unsuccessful response
```

说明:

此Python 脚本通过向提供的 URL 发送 HTTP GET 请求来检查网站的状态。它可以帮助您监控网站及其响应代码的可用性。

10.2自动 FTP 传输

python 复制代码
```
# Python script to automate FTP file transfers
from ftplib import FTP

def ftp_file_transfer(host, username, password, local_file_path, remote_file_path):
    with FTP(host) as ftp:
        ftp.login(user=username, passwd=password)
        with open(local_file_path, 'rb') as f:
            ftp.storbinary(f'STOR {remote_file_path}', f)
```

说明:

此Python 脚本使用 FTP 协议自动进行文件传输。它连接到 FTP 服务器,使用提供的凭据登录,并将本地文件上传到指定的远程位置。

10.3网络配置设置

python 复制代码
```
# Python script to automate network device configuration
from netmiko import ConnectHandler

def configure_network_device(host, username, password, configuration_commands):
    device = {
        'device_type': 'cisco_ios',
        'host': host,
        'username': username,
        'password': password,
    }
    with ConnectHandler(**device) as net_connect:
        net_connect.send_config_set(configuration_commands)
```

说明:

此Python 脚本使用 netmiko 库自动配置网络设备,例如 Cisco路由器和交换机。您可以提供配置命令列表,此脚本将在目标设备上执行它们。

11. 数据清理和转换

11.1从数据中删除重复项

python 复制代码
```
# Python script to remove duplicates from data
import pandas as pd

def remove_duplicates(data_frame):
    cleaned_data = data_frame.drop_duplicates()
    return cleaned_data
```

说明:

此Python脚本能够利用 pandas 从数据集中删除重复行,这是确保数据完整性和改进数据分析的简单而有效的方法。

11.2数据标准化

python 复制代码
```
# Python script for data normalization
import pandas as pd

def normalize_data(data_frame):
    normalized_data = (data_frame - data_frame.min()) / (data_frame.max() -  data_frame.min())
    return normalized_data
```

说明:

此Python 脚本使用最小-最大标准化技术对数据进行标准化。它将数据集中的值缩放到 0 到 1 之间,从而更容易比较不同的特征。

11.3处理缺失值

python 复制代码
```
# Python script to handle missing values in data
import pandas as pd

def handle_missing_values(data_frame):
    filled_data = data_frame.fillna(method='ffill')
    return filled_data
```

说明:

此Python 脚本使用 pandas 来处理数据集中的缺失值。它使用前向填充方法,用先前的非缺失值填充缺失值。

12. 自动化 PDF 操作

12.1从PDF中提取文本

python 复制代码
```
# Python script to extract text from PDFs
import PyPDF2

def extract_text_from_pdf(file_path):
    with open(file_path, 'rb') as f:
        pdf_reader = PyPDF2.PdfFileReader(f)
        text = ''
        for page_num in range(pdf_reader.numPages):
            page = pdf_reader.getPage(page_num)
            text += page.extractText()
    return text
```

说明:

此Python 脚本使用PyPDF2库从PDF文件中提取文本。它读取PDF的每一页并将提取的文本编译为单个字符串。

12.2合并多个PDF

python 复制代码
```
# Python script to merge multiple PDFs into a single PDF
import PyPDF2

def merge_pdfs(input_paths, output_path):
    pdf_merger = PyPDF2.PdfMerger()
    for path in input_paths:
        with open(path, 'rb') as f:
            pdf_merger.append(f)
    with open(output_path, 'wb') as f:
        pdf_merger.write(f)
```

说明:

此Python脚本将多个PDF文件合并为一个PDF文档。它可以方便地将单独的PDF、演示文稿或其他文档合并为一个统一的文件。

12.3添加密码保护

python 复制代码
```
# Python script to add password protection to a PDF
import PyPDF2

def add_password_protection(input_path, output_path, password):
    with open(input_path, 'rb') as f:
        pdf_reader = PyPDF2.PdfFileReader(f)
        pdf_writer = PyPDF2.PdfFileWriter()
        for page_num in range(pdf_reader.numPages):
            page = pdf_reader.getPage(page_num)
            pdf_writer.addPage(page)
    pdf_writer.encrypt(password)  # 应该在循环外部调用一次
    with open(output_path, 'wb') as output_file:
        pdf_writer.write(output_file)
```

​​​​​​说明:

此Python脚本为PDF文件添加密码保护。它使用密码对PDF进行加密,确保只有拥有正确密码的人才能访问内容。

13. 自动化GUI

13.1自动化鼠标和键盘

python 复制代码
```
# Python script for GUI automation using pyautogui
import pyautogui

def automate_gui():
    # Your code here for GUI automation using pyautogui
    pass
```

说明:

此Python 脚本使用 pyautogui 库,通过模拟鼠标移动、单击和键盘输入来自动执行 GUI 任务。它可以与 GUI 元素交互并执行单击按钮、键入文本或导航菜单等操作。

13.2创建简单的 GUI 应用程序

python 复制代码
```
# Python script to create simple GUI applications using tkinter
import tkinter as tk

def create_simple_gui():
    # Your code here to define the GUI elements and behavior
    pass
```

说明:

此Python 脚本可以使用 tkinter 库创建简单的图形用户界面 (GUI)。您可以设计窗口、按钮、文本字段和其他 GUI 元素来构建交互式应用程序。

13.3处理GUI事件

python 复制代码
```
# Python script to handle GUI events using tkinter
import tkinter as tk

def handle_gui_events():
    pass

def on_button_click():
    # Your code here to handle button click event
    print("Button clicked!")

root = tk.Tk()
button = tk.Button(root, text="Click Me", command=on_button_click)
button.pack()
root.mainloop()
```

说明:

此Python 脚本演示了如何使用 tkinter 处理 GUI 事件。它创建一个按钮小部件并定义了一个回调函数,该函数将在单击按钮时执行。

14. 自动化测试

14.1使用 Python 进行单元测试

python 复制代码
```
# Python script for web testing using Selenium
from selenium import webdriver

def perform_web_test():
    driver = webdriver.Chrome()
    driver.get("https://www.example.com")
    # Your code here to interact with web elements and perform tests
    driver.quit()
```

说明:

该Python脚本使用unittest模块来执行单元测试。它包括add 函数的测试用例,用正数、负数和零值检查其行为。

14.2用于 Web 测试的 Selenium

python 复制代码
```
# Python script for web testing using Selenium
from selenium import webdriver

def perform_web_test():
    driver = webdriver.Chrome()
    driver.get("https://www.example.com")
    # Your code here to interact with web elements and perform tests
    driver.quit()
```

说明:

此Python 脚本使用 Selenium 库来自动化 Web 测试。它启动 Web 浏览器,导航到指定的 URL,并与 Web 元素交互以测试网页的功能。

14.3测试自动化框架

python 复制代码
```
# Python script for building test automation frameworks
# Your code here to define the framework architecture and tools
```

说明:

构建测试自动化框架需要仔细的规划和组织。该脚本是一个创建自定义的、适合您的特定项目需求的测试自动化框架的起点。它涉及定义架构、选择合适的工具和库以及创建可重用的测试函数。

15. 自动化云服务

15.1向云空间上传文件

python 复制代码
```
# Python script to automate uploading files to cloud storage
# Your code here to connect to a cloud storage service (e.g., AWS S3, Google Cloud Storage)
# Your code here to upload files to the cloud storage
```

说明:

自动将文件上传到云存储的过程可以节省时间并简化工作流程。利用相应的云服务API,该脚本可作为将云存储功能集成到 Python 脚本中的起点。

15.2管理AWS资源

​​​​​

python 复制代码
```
# Python script to manage AWS resources using Boto3
import boto3

def create_ec2_instance(instance_type, image_id, key_name, security_group_ids):
    ec2 = boto3.resource('ec2')
    instance = ec2.create_instances(
        ImageId=image_id,
        InstanceType=instance_type,
        KeyName=key_name,
        SecurityGroupIds=security_group_ids,
        MinCount=1,
        MaxCount=1
    )
    return instance[0].id
```

说明:

此Python 脚本使用 Boto3 库与 Amazon Web Services (AWS) 交互并创建 EC2 实例。它可以扩展以执行各种任务,例如创建 S3 buckets、管理 IAM 角色或启动 Lambda 函数。

15.3自动化 Google 云端硬盘

python 复制代码
```
# Python script to automate interactions with Google Drive
# Your code here to connect to Google Drive using the respective API
# Your code here to perform tasks such as uploading files, creating folders, etc.
```

说明:

以编程方式与Google Drive 交互可以简化文件管理和组织。该脚本可以充当一个利用 Google Drive API 将 Google Drive 功能集成到 Python 脚本中的起点。

16. 财务自动化

16.1分析股票价格

python 复制代码
```
# Python script for stock price analysis
# Your code here to fetch stock data using a financial API (e.g., Yahoo Finance)
# Your code here to analyze the data and derive insights
```

说明:

自动化获取和分析股票价格数据的过程对投资者和金融分析师来说是十分有益的。该脚本可作为一个使用金融 API 将股票市场数据集成到 Python 脚本中的起点。

16.2货币汇率

python 复制代码
```
# Python script to fetch currency exchange rates
# Your code here to connect to a currency exchange API (e.g., Fixer.io, Open Exchange Rates)
# Your code here to perform currency conversions and display exchange rates
```

说明:

此Python 脚本利用货币兑换 API 来获取和显示不同货币之间的汇率。它可用于财务规划、国际贸易或旅行相关的应用程序。

16.3预算追踪

python 复制代码
```
# Python script for budget tracking and analysis
# Your code here to read financial transactions from a CSV or Excel file
# Your code here to calculate income, expenses, and savings
# Your code here to generate reports and visualize budget data
```

说明:

此Python 脚本使您能够通过从 CSV 或 Excel 文件读取财务交易来跟踪和分析预算。它反映有关收入、支出和储蓄的情况,帮助您作出明智的财务决策。

17. 自然语言处理

17.1情感分析

python 复制代码
```
# Python script for sentiment analysis using NLTK or other NLP libraries
importnltk
fromnltk.sentiment import SentimentIntensityAnalyzer

defanalyze_sentiment(text):
    nltk.download('vader_lexicon')
    sia = SentimentIntensityAnalyzer()
    sentiment_score = sia.polarity_scores(text)
    return sentiment_score
```

说明:

此Python 脚本使用 NLTK 库对文本数据进行情感分析。它计算情绪分数,这个分数表示所提供文本的积极性、中立性或消极性。

17.2文本摘要

python 复制代码
```
# Python script for text summarization using NLP techniques
# Your code here to read the text data and preprocess it (e.g., removing stop words)
# Your code here to generate the summary using techniques like TF-IDF, TextRank, or BERT```

说明:

文本摘要自动执行为冗长的文本文档创建简洁摘要的过程。该脚本可作为使用NLP 库实现各种文本摘要技术的起点。

17.3语言翻译

python 复制代码
```
# Python script for language translation using NLP libraries
# Your code here to connect to a translation API (e.g., Google Translate, Microsoft Translator)
# Your code here to translate text between different languages```

说明:

自动化语言翻译可以促进跨越语言障碍的沟通。该脚本可适配连接各种翻译API并支持多语言通信。

结论

在本文中,我们探索了17个可以跨不同领域自动执行各种任务的 Python 脚本。从网页抓取和网络自动化到机器学习和物联网设备控制,Python 的多功能性使我们能够高效地实现各种流程的自动化。

自动化不仅可以节省时间和精力,还可以降低出错风险并提高整体生产力。通过自定义和构建这些脚本,您可以创建定制的自动化解决方案来满足您的特定需求。

还等什么呢?立即开始使用Python 实现工作自动化,体验简化流程和提高效率的力量。

一些经常被问到的问题

1.Python适合自动化吗?

绝对适合!Python 因其简单性、可读性和丰富的库而成为最流行的自动化编程语言之一。它可以自动执行多种任务,因此成为了开发人员和 IT 专业人员的最佳选择。

2.使用 Python 自动化任务有哪些好处?

使用Python 自动化任务具有多种好处,包括提高效率、减少人工错误、节省时间和提高生产力。Python 的易用性和丰富的库生态系统使其成为自动化项目的绝佳选择。

3. 我可以在我的项目中使用这些脚本吗?

是的,您可以使用这些脚本作为您的项目的起点。但是,请记住,提供的代码片段仅用于说明目的,可能需要修改才能满足您的特定要求和API。

4. 我需要安装任何库来运行这些脚本吗?

是的,某些脚本利用外部库。确保在运行脚本之前安装所需的库。您可以使用"pip install <library-name>"来安装任何缺少的库。

5. 我可以将这些脚本用于商业用途吗?

本文中提供的脚本旨在用于教育和说明。虽然您可以将它们用作项目的基础,但请查看并始终遵守商业项目中使用的任何外部库、API或服务的条款和条件。

6. 如何针对我的特定项目进一步优化这些脚本?

要根据您的特殊目的优化这些脚本,您可能需要修改代码、添加错误处理、自定义数据处理步骤以及与必要的API 或服务集成。您要始终记得彻底测试脚本以确保它们满足您的要求。

7. 我可以使用Python自动执行复杂的任务吗?

是的,Python能够自动执行跨多个领域的复杂任务,包括数据分析、机器学习、网络抓取等。借助正确的库和算法,您可以有效地处理复杂的任务。

8. 自动化任务时是否有任何安全考虑?

是的,在自动化涉及敏感数据、API或设备的任务时,实施安全措施至关重要。使用安全连接(HTTPS、SSH),避免对敏感信息进行硬编码,并考虑访问控制和身份验证来保护您的系统和数据。

THE END !

文章结束,感谢阅读。您的点赞,收藏,评论是我继续更新的动力。大家有推荐的公众号可以评论区留言,共同学习,一起进步。

相关推荐
i嗑盐の小F1 分钟前
【 ACM独立出版,见刊后1个月检索!!!】第二届通信网络与机器学习国际学术会议(CNML 2024,10月25-27)
网络·图像处理·人工智能·深度学习·算法·机器学习·计算机视觉
WZF-Sang1 分钟前
【MySQL】数据类型【mysql当中各自经典的数据类型的学习和使用】
linux·数据库·sql·学习·mysql·adb
我命由我123451 分钟前
ADB 之 logcat 极简小抄(过滤日志、保存日志到文件)
android·运维·adb·android studio·安卓·运维开发·android-studio
李yufei2 分钟前
基于AlexNet实现猫狗大战
人工智能·计算机视觉
玥轩_5214 分钟前
网络安全 DVWA通关指南 DVWA SQL Injection (Blind SQL盲注)
sql·安全·web安全·网络安全·dvwa·sql盲注
迷茫运维路5 分钟前
mysql5.7常用操作命令手册
运维·数据库
正在走向自律15 分钟前
4.提升客户服务体验:ChatGPT在客服中的应用(4/10)
人工智能·机器学习·chatgpt·职场和发展
不想CRUD的小凯17 分钟前
【AI大语言模型应用】使用Ollama搭建本地大语言模型
人工智能·语言模型·自然语言处理
.生产的驴17 分钟前
Docker 消息队列RabbitMQ 安装延迟消息插件
运维·spring boot·后端·docker·容器·rabbitmq·java-rabbitmq
红米煮粥17 分钟前
神经网络-MNIST数据集训练
人工智能·深度学习·神经网络