python入门脚本_十个实用Python脚本,没想到
1. 定时提醒脚本这个脚本可以设置定时提醒,比如在每天特定时间弹出消息,提醒你喝水、休息等import time import schedule defreminder(message):"""显示提醒消息。
参数: message: 要显示的提醒消息 """ print(f"提醒:{message}") # 设置每天早上 9 点提醒喝水 schedule.every().day.at(
"09:00").do(reminder, message="该喝水啦!") # 设置每隔 30 分钟提醒休息 schedule.every(30).minutes.do(reminder, message=
"起来活动一下!") whileTrue: schedule.run_pending()# 运行所有可以运行的任务 time.sleep(1)# 每秒检查一次2. 文本文件词频统计该脚本可以读取文本文件,统计每个单词的出现频率,并按频率排序输出结果。
import re from collections import Counter defcount_word_frequency(file_path):"""统计文本文件中的词频 参数: file_path: 文本文件路径。
"""with open(file_path, r, encoding=utf-8) as f: text = f.read() words = re.findall(
r\b\w+\b, 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 defgenerate_password。
(length=12, include_digits=True, include_symbols=True):"""生成随机密码 参数: 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 defcheck_internet_connection(hostname=
"www.baidu.com"):""" 检查网络连接是否正常 参数: 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-8import json defwrite_json_to_file(data, file_path)。
:"""将 JSON 数据写入文件 参数: 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-8from pytube import YouTube 。
想省去手游时长,却又不想放弃游戏收益?试试【星界云手机】吧!它不仅可以实现云端托管手游,24小时不间断挂机,还能配合挂机脚本,轻松完成日常任务,让你事半功倍,游戏收益翻倍!
defdownload_youtube_subtitles(video_url, output_path="subtitles.srt"):"""从 YouTube 视频下载字幕 参数: 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-8from PIL import Image defconvert_image_format。
(input_path, output_path, output_format="PNG"):"""转换图片格式 参数: 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-8import requests defget_weather(city):"""获取指定城市的天气预报 参数: 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-8import time import os 。
defcountdown_timer(seconds):""" 创建一个简单的倒计时器 参数: seconds: 倒计时时间(秒) """while seconds > 。
0: print(f"倒计时:{seconds} 秒") time.sleep(1) seconds -= 1 print("时间到!") os.system(
"say Times up!") if __name__ == __main__: # 示例用法 countdown_timer(10) 10. 批量压缩图片这个脚本可以批量压缩指定目录下的图片,减小图片文件大小。
# encoding=UTF-8import os from PIL import Image defcompress_images(directory, quality=80):"""批量压缩图片。
参数: 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)
想省去手游时长,却又不想放弃游戏收益?试试【星界云手机】吧!它不仅可以实现云端托管手游,24小时不间断挂机,还能配合挂机脚本,轻松完成日常任务,让你事半功倍,游戏收益翻倍!
本站所有文章、数据、图片均来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:631580315@qq.com