十个常见Python 脚本(绝对实用)

十个常见Python 脚本(绝对实用)

1、定时提醒脚本

该脚本可以设置定时提醒,例如在每天的某个时间点弹出提醒消息,提醒你喝水、休憩等。

import time
import schedule


def reminder(message):
    """ 显示提醒消息。
    Args:
    message: 要显示的提醒消息。
    """
    print(f"提醒:{message}")


# 设置每天早上 9 点提醒喝水
schedule.every().day.at("09:00").do(reminder, message="该喝水啦!")

# 设置每隔 30 分钟提醒休憩
schedule.every(30).minutes.do(reminder, message="起来活动一下!")

while True:
    schedule.run_pending()# 运行所有可以运行的任务
    time.sleep(1)# 每秒检查一次

2、文本文件词频统计

该脚本可以读取文本文件,统计每个单词出现的频率,并按频率排序输出结果。

import re
from collections import Counter


def count_word_frequency(file_path):
    """统计文本文件中的词频。
    Args:
    file_path: 文本文件路径。
    """
    with open(file_path, 'r', encoding='utf-8') as f:
        text = f.read()
    words = re.findall(r'w+', text.lower())
    word_counts = Counter(words)
    for word, count in word_counts.most_common():
        print(f"{word}: {count}")
if __name__ == '__main__':
    # 示例用法
    count_word_frequency("my_text_file.txt")

3、生成随机密码

该脚本可以生成指定长度和字符集的随机密码,例如包含大小写字母、数字和特殊字符的强密码。

import random
import string


def generate_password(length=12, include_digits=True, include_symbols=True):
    """生成随机密码。

    Args:
        length: 密码长度,默认为 12。
        include_digits: 是否包含数字,默认为 True。
        include_symbols: 是否包含特殊字符,默认为 True。
    """
    characters = string.ascii_letters
    if include_digits:
        # string.digits输出:0123456789
        characters += string.digits
    if include_symbols:
        # string.punctuation 是一个字符串,包含所有的ASCII标点符号字符。
        characters += string.punctuation
    password = ''.join(random.choice(characters) for _ in range(length))
    return password


if __name__ == '__main__':
    # 示例用法
    password = generate_password()
    print(password)

4、检查网络连接

该脚本可以检查网络连接是否正常,例如 ping 指定网站,如果无法 ping 通则提示网络连接异常。

import os


def check_internet_connection(hostname="www.baidu.com"):
    """
    检查网络连接是否正常。
    Args:
        hostname: 要 ping 的主机名,默认为 www.baidu.com。
    """
    response = os.system(f"ping {hostname}")
    if response == 0:
        print(f"{hostname} 可达,网络连接正常。")
    else:
        print(f"{hostname} 不可达,网络连接异常!")


if __name__ == "__main__":
    # 示例用法
    check_internet_connection()

5、将 JSON 数据写入文件

该脚本可以将 Python 字典或列表等数据结构转换为 JSON 格式,并写入到文件中

#coding=utf-8
import json


def write_json_to_file(data, file_path):
    """将 JSON 数据写入文件。
    Args:
        data: 要写入的数据,可以是字典、列表等。
        file_path: 要写入的文件路径。
    """
    with open(file_path, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=4,ensure_ascii=False)

if __name__ == '__main__':
    # 示例用法
    data = {"name": "李", "age": 25, "city": "New York"}
    write_json_to_file(data, "data.json")

6、从 YouTube 视频下载字幕

该脚本可以从 YouTube 视频下载字幕文件,例如 SRT 格式的字幕。

# encoding=utf-8
from pytube import YouTube


def download_youtube_subtitles(video_url, output_path="subtitles.srt"):
    """从 YouTube 视频下载字幕。

    Args:
        video_url: YouTube 视频链接。
        output_path: 字幕文件保存路径,默认为 "subtitles.srt"。
    """
    try:
        yt = YouTube(video_url)
        caption = yt.captions.get_by_language_code('en')  # 下载英文
        if caption:
            caption.download(output_path)
            print(f"字幕已下载到: {output_path}")
        else:
            print("未找到字幕!")
    except Exception as e:
        print(f"下载字幕时出错:{e}")

if __name__ == "__main__":
    # 示例用法
    download_youtube_subtitles("https://www.youtube.com/watch?v=YOUR_VIDEO_ID")

7、图片格式转换

该脚本可以将图片从一种格式转换为另一种格式,例如将 JPG 格式转换为 PNG 格式

# encoding=utf-8
from PIL import Image


def convert_image_format(input_path, output_path, output_format="PNG"):
    """转换图片格式。
  
    Args:
        input_path: 输入图片路径。
        output_path: 输出图片路径。
        output_format: 输出图片格式,默认为 PNG。
    """
    try:
        img = Image.open(input_path)
        img.save(output_path, format=output_format)
        print(f"图片已转换为 {output_format} 格式,保存到: {output_path}")
    except Exception as e:
        print(f"转换图片格式时出错:{e}")

if __name__ == "__main__":
    # 示例用法
    convert_image_format("input.jpg", "output.png")

8、获取天气预报

该脚本可以获取指定城市的天气预报信息,例如温度、湿度、风力等。

# encoding=UTF-8
import requests


def get_weather(city):
    """获取指定城市的天气预报。
  
    Args:
        city: 城市名称。
    """
    api_key = "*********"  # 将 YOUR_API_KEY 替换为你的 API 密钥
    base_url = "http://api.openweathermap.org/data/2.5/weather?"
    complete_url = f"{base_url}appid={api_key}&q={city}"
    response = requests.get(complete_url)
    data = response.json()

    if data["cod"] != "404":
        main = data['main']
        temperature = main['temp'] - 273.15  # 转换为摄氏度
        humidity = main['humidity']
        weather_description = data['weather'][0]['description']
        print(f"{city} 的天气预报:")
        print(f"温度: {temperature:.1f}°C")
        print(f"湿度: {humidity}%")
        print(f"天气描述: {weather_description}")
    else:
        print(f"未找到 {city} 的天气信息。")

if __name__ == "__main__":
    # 示例用法
    get_weather("Beijing")

9、创建简单的倒计时器

该脚本可以创建一个简单的倒计时器,例如设定倒计时时间,并在倒计时结束后发出提示音。

# encoding=UTF-8
import time
import os


def countdown_timer(seconds):
    """ 创建一个简单的倒计时器。

    Args:
        seconds: 倒计时时间(秒)。
    """
    while seconds > 0:
        print(f"倒计时:{seconds} 秒")
        time.sleep(1)
        seconds -= 1
    print("时间到!")
    os.system("say 'Time's up!'")


if __name__ == '__main__':
    # 示例用法
    countdown_timer(10)

10、批量压缩图片

该脚本可以批量压缩指定目录下的图片,减小图片文件大小

# encoding=UTF-8
import os
from PIL import Image


def compress_images(directory, quality=80):
    """批量压缩图片。

    Args:
        directory: 要处理的目录路径。
        quality: 压缩质量,默认为 80 (0-100)。
    """
    for filename in os.listdir(directory):
        if filename.endswith((".jpg", ".jpeg", ".png")):
            img_path = os.path.join(directory, filename)
            img = Image.open(img_path)
            img.save(img_path, optimize=True, quality=quality)
            print(f"已压缩: {filename}")


if __name__ == "__main__":
    # 示例用法
    compress_images("/path/to/your/images", quality=70)
© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
KM178v的头像 - 鹿快
评论 共4条

请登录后发表评论

    暂无评论内容