在这个快节奏、高效率的时代,掌握时间管理和信息整理的艺术尤为重要。今天分享一系列Python自动化脚本,帮助提升工作效率和信息处理能力。从时间管理到数据整理,从内容创作到邮件分析,这些脚本覆盖了日常工作和生活中的多个方面,助你以更智能、更高效的方式完成任务。
1.番茄钟(Pomodura)
番茄工作法是提高生产力的最简单方法之一。将工作时间划分为25分钟的工作段,每段之间用5分钟的短暂休息来分隔。
这个Python自动化脚本进一步强化了番茄工作法,在计时器结束时会自动锁定你的设备,确保你的休息时间。
import tkinter as tk
import time
import ctypes
import os
from threading import Timer
class PomodoroTimer:
def __init__(self, root):
self.root = root
self.root.title("Pomodoro Timer")
self.root.geometry("300x200")
self.time_var = tk.StringVar()
self.time_var.set("25:00")
self.running = False
self.paused = False
self.remaining_time = 25 * 60 # 25 minutes
self.label = tk.Label(root, textvariable=self.time_var, font=("Helvetica", 48))
self.label.pack(pady=20)
self.start_button = tk.Button(root, text="Start", command=self.start_timer)
self.start_button.pack(side=tk.LEFT, padx=10)
self.pause_button = tk.Button(root, text="Pause", command=self.pause_timer)
self.pause_button.pack(side=tk.LEFT, padx=10)
self.reset_button = tk.Button(root, text="Reset", command=self.reset_timer)
self.reset_button.pack(side=tk.LEFT, padx=10)
def update_time(self):
if self.running:
minutes, seconds = divmod(self.remaining_time, 60)
self.time_var.set(f"{minutes:02}:{seconds:02}")
if self.remaining_time > 0:
self.remaining_time -= 1
self.root.after(1000, self.update_time)
else:
self.running = False
self.lock_screen()
def start_timer(self):
if not self.running:
self.running = True
self.paused = False
self.update_time()
def pause_timer(self):
if self.running:
self.running = False
self.paused = True
def reset_timer(self):
self.running = False
self.paused = False
self.remaining_time = 25 * 60
self.time_var.set("25:00")
def lock_screen(self):
if os.name == 'nt': # Windows
ctypes.windll.user32.LockWorkStation()
elif os.name == 'posix': # macOS and Linux
# 这是一个占位符,因为在macOS/Linux上锁定屏幕通常需要不同的处理
# 对于macOS,使用:os.system('/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend')
# 对于Linux,使用:os.system('gnome-screensaver-command --lock')
print("Locking screen on macOS/Linux is not implemented in this script.")
if __name__ == "__main__":
root = tk.Tk()
app = PomodoroTimer(root)
root.mainloop()
2 今日视野(TodayScope)
这个自动化脚本能够自动为你汇总当天的头条新闻、历史事件和星座运势,一并呈现,一目了然。
import tkinter as tk
from tkinter import ttk
import requests
from bs4 import BeautifulSoup
def get_trending_news():
"""Fetch and return trending news headlines."""
url = "http://newsapi.org/v2/top-headlines?country=us&apiKey=CREATE_YOUR_OWN"
page = requests.get(url).json()
articles = page["articles"]
results = [ar["title"] for ar in articles[:10]]
headlines = "\n".join(f"{i + 1}. {title}" for i, title in enumerate(results))
return headlines
def get_horoscope(sign_name):
"""Fetch and return horoscope for the specified sign."""
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
signs = {
'aries':1, 'taurus':2, 'gemini':3, 'cancer':4,
'leo':5, 'virgo':6, 'libra':7, 'scorpio':8,
'sagittarius':9, 'capricorn':10, 'aquarius':11, 'pisces':12
}
sign_id = signs.get(sign_name.lower())
if sign_id is None:
return "Sign not found."
url = f'https://www.horoscope.com/us/horoscopes/general/horoscope-general-daily-today.aspx?sign={sign_id}'
res = requests.get(url, headers=headers)
soup = BeautifulSoup(res.text, 'html.parser')
try:
horoscope_text = soup.select('.main-horoscope p')[0].getText().strip().capitalize()
sign = soup.select('h1')[0].getText().strip().capitalize()
return f"{sign} Horoscope: {horoscope_text}"
except:
return "Could not fetch the horoscope."
def get_history_today():
"""Fetch and return historical events that happened on this day."""
url = 'https://www.onthisday.com/'
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
history_list = soup.select('.event')[:5] # 限制为5个事件
events = [event.getText().strip() for event in history_list]
history_text = "\n".join(events)
return history_text
def show_popup():
# 从每个函数获取信息
news = get_trending_news()
horoscope = get_horoscope('aries') # 将'aries'替换为所需星座
history = get_history_today()
# 创建主Tkinter窗口
root = tk.Tk()
from datetime import datetime
# 获取当前日期以显示在GUI上
current_date = datetime.now()
formatted_date = current_date.strftime("%d %b %Y")
root.title(f"Daily Update: {formatted_date}")
root.geometry("500x600")
root.configure(bg="#f0f0f5") # 设置背景颜色
# 设置带滚动条的画布
canvas = tk.Canvas(root, bg="#f0f0f5")
scrollbar = ttk.Scrollbar(root, orient="vertical", command=canvas.yview)
scrollable_frame = tk.Frame(canvas, bg="#f0f0f5")
scrollable_frame.bind(
"<Configure>",
lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
canvas.configure(yscrollcommand=scrollbar.set)
# 定义画布、滚动条和颜色
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
header_font = ("Arial", 14, "bold")
text_font = ("Arial", 12)
colors_list = ["#E4E0E1","#FFDDC1", "#D4E157", "#81D4FA", "#FFAB91", "#A5D6A7", "#FFF59D", "#CE93D8", "#B39DDB", "#90CAF9", "#FFE082", "#FFCCBC", "#AED581", "#FFE0B2", "#80CBC4", "#F48FB1"]
section_bg = random.choice(colors_list)
# 创建一个部分的函数
def create_section(parent, title, content, color):
frame = tk.Frame(parent, bg=color, pady=10, padx=10)
frame.pack(fill="x", pady=5, padx=5)
title_label = tk.Label(frame, text=title, font=header_font, bg=color, fg="#333333")
title_label.pack(anchor="w", pady=(0, 5))
content_label = tk.Label(frame, text=content, justify="left", wraplength=450, bg=color, fg="#000000")
content_label.pack(anchor="w")
return frame
# 添加热门新闻部分
create_section(scrollable_frame, "Trending News", news, section_bg)
# 添加星座运势部分
create_section(scrollable_frame, "Horoscope", horoscope, section_bg)
# 添加历史事件部分
create_section(scrollable_frame, "On This Day", history, section_bg)
# 在底部添加关闭按钮
close_button = ttk.Button(scrollable_frame, text="Close", command=root.destroy)
close_button.pack(pady=20)
root.mainloop()
# 运行脚本并在启动时显示弹出窗口
if __name__ == "__main__":
show_popup()
3.潮流股票(TrendyStocks)
股市里,公众关注度往往与股价波动息息相关。这个自动化脚本能追踪股票的流行趋势,帮你捕捉市场热点,从而做出更精准的投资选择。它能够帮助你快速了解哪些股票正受到市场关注,哪些则不然,是投资研究的得力助手。
#!pip install pytrends
from pytrends.request import TrendReq
import matplotlib.pyplot as plt
# 函数:获取趋势数据
def get_google_trends_data(keywords, timeframe='today 3-m', geo='US'):
pytrends = TrendReq(hl='en-US', tz=360)
# 构建请求数据
pytrends.build_payload(keywords, cat=0, timeframe=timeframe, geo=geo, gprop='')
# 获取随时间变化的兴趣度数据
interest_over_time_df = pytrends.interest_over_time()
return interest_over_time_df
# 示例关键词,与你的文章相关
STOCKS = ["AMZN", "MSFT", "NVDA", "AAPL", "GOOG"]
# 获取趋势数据
trends_data = get_google_trends_data(STOCKS)
# 绘制数据图表
plt.figure(figsize=(20, 12))
trends_data.plot(title='Google Trends for STOCKS')
plt.xlabel('Date')
plt.ylabel('Interest Over Time')
plt.show()
4.整洁化(Neatify)
你是否有面对杂乱无章的下载文件夹感到头疼的时候?是否有急需文件却找不到的时候?并且尝试整理却总是失败。
这个自动化脚本几分钟内帮你解决文件管理难题。只需指定路径,就会自动:
- 分类整理:按文件扩展名自动分类存放。
- 去除重复:通过哈希值检测,删除重复文件。
- 时间排序:根据文件日期自动归档,方便查找。
import os
import shutil
import hashlib
from datetime import datetime
def get_file_hash(file_path):
"""Calculate the SHA-256 hash of a file."""
with open(file_path, 'rb') as f:
return hashlib.sha256(f.read()).hexdigest()
def organize_by_date_and_extension(folder_path):
"""Organize files by date, then by extension, and handle duplicates."""
# 在根目录创建“Duplicates”文件夹
duplicates_folder = os.path.join(folder_path, '_Duplicates')
os.makedirs(duplicates_folder, exist_ok=True)
# 字典,用于存储文件哈希值以检测重复文件
file_hashes = {}
# 遍历目录中的所有文件
all_files = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]
for file_path in all_files:
# 获取文件的修改日期
modification_time = os.path.getmtime(file_path)
modification_date = datetime.fromtimestamp(modification_time).strftime('%Y-%m-%d')
# 如不存在,则创建修改日期对应的文件夹
date_folder = os.path.join(folder_path, modification_date)
os.makedirs(date_folder, exist_ok=True)
# 计算文件哈希值
file_hash = get_file_hash(file_path)
# 检测重复文件
if file_hash in file_hashes:
# 文件是重复的,移动到“Duplicates”文件夹
shutil.move(file_path, os.path.join(duplicates_folder, os.path.basename(file_path)))
print(f"Moved duplicate file {os.path.basename(file_path)} to Duplicates folder.")
else:
# 存储文件哈希值以避免将来的重复
file_hashes[file_hash] = file_path
# 将文件移动到日期文件夹
new_path = os.path.join(date_folder, os.path.basename(file_path))
shutil.move(file_path, new_path)
# 在日期文件夹内按扩展名组织文件
_, extension = os.path.splitext(new_path)
extension = extension.lower()
extension_folder = os.path.join(date_folder, extension[1:]) # 从扩展名中去除点
os.makedirs(extension_folder, exist_ok=True)
# 将文件移动到其扩展名对应的文件夹
shutil.move(new_path, os.path.join(extension_folder, os.path.basename(new_path)))
print(f"Moved {os.path.basename(new_path)} to {extension_folder}.")
print("Files organized by date, extension, and duplicates handled successfully!")
if __name__ == "__main__":
# 指定要组织整理的目录
folder_path = input("Enter the path to the folder to organize: ")
organize_by_date_and_extension(folder_path)
5.时钟工作(ClockWork)
时间追踪是提升效率的关键,帮助我们发现工作模式、优化流程并保持专注。但手动记录易出错、打断工作。这个自动化脚本简化了流程,自动追踪任务时间,实时监控并记录日志,让你专注于核心工作。
应用场景:
- 时间追踪器:提高工作效率。
- 模型训练追踪器:优化研发流程。
import tkinter as tk
from tkinter import ttk, messagebox
import csv
import time
from datetime import datetime
class TaskTrackerApp:
def __init__(self, root):
self.root = root
self.root.title("ClockWork: Time Tracking Made Easy")
self.task_name_var = tk.StringVar()
self.probable_time_var = tk.IntVar()
self.start_time = None
# UI元素配置
self.setup_ui()
# 如果日志文件不存在,则创建
self.create_log_file()
def setup_ui(self):
style = ttk.Style()
style.configure("TLabel", font=("Helvetica", 12))
style.configure("TButton", font=("Helvetica", 12, 'bold'), padding=6)
# UI元素
ttk.Label(self.root, text="Task Name:", foreground="blue").grid(row=0, column=0, padx=10, pady=10)
ttk.Entry(self.root, textvariable=self.task_name_var, width=30).grid(row=0, column=1, padx=10, pady=10)
ttk.Label(self.root, text="Probable Time (minutes):", foreground="blue").grid(row=1, column=0, padx=10, pady=10)
ttk.Entry(self.root, textvariable=self.probable_time_var, width=30).grid(row=1, column=1, padx=10, pady=10)
ttk.Button(self.root, text="Start Task", command=self.start_task).grid(row=2, column=0, padx=10, pady=10)
self.stop_button = ttk.Button(self.root, text="Stop Task", command=self.stop_task, state=tk.DISABLED)
self.stop_button.grid(row=2, column=1, padx=10, pady=10)
ttk.Button(self.root, text="Reset", command=self.reset_task).grid(row=3, column=0, padx=10, pady=10)
ttk.Button(self.root, text="View Time Logs", command=self.view_time_logs).grid(row=3, column=1, padx=10, pady=10)
self.timer_label = ttk.Label(self.root, text="00:00:00", font=("Helvetica", 18, 'bold'), foreground="green")
self.timer_label.grid(row=4, column=0, columnspan=2, padx=10, pady=20)
def create_log_file(self):
with open("time_log.csv", "a", newline="") as file:
writer = csv.writer(file)
if file.tell() == 0:
writer.writerow(['Task Name', 'Probable Time (minutes)', 'Start Time', 'End Time', 'Time Spent (minutes)', 'Time Difference (minutes)'])
def start_task(self):
task_name = self.task_name_var.get()
if task_name:
self.start_time = time.time()
self.start_button.config(state=tk.DISABLED)
self.stop_button.config(state=tk.NORMAL)
self.update_timer()
def stop_task(self):
self.stop_button.config(state=tk.DISABLED)
self.start_button.config(state=tk.NORMAL)
time_spent = round((time.time() - self.start_time) / 60, 2)
self.log_time(time_spent)
def update_timer(self):
if self.start_time:
time_spent = time.time() - self.start_time
time_str = time.strftime('%H:%M:%S', time.gmtime(time_spent))
self.timer_label.config(text=time_str)
self.root.after(1000, self.update_timer)
def log_time(self, time_spent):
end_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
time_diff = round(time_spent - self.probable_time_var.get(), 2)
with open("time_log.csv", "a", newline="") as file:
writer = csv.writer(file)
writer.writerow([self.task_name_var.get(), self.probable_time_var.get(), self.start_time, end_time, time_spent, time_diff])
def reset_task(self):
self.task_name_var.set("")
self.probable_time_var.set("")
self.timer_label.config(text="00:00:00")
self.start_button.config(state=tk.NORMAL)
self.stop_button.config(state=tk.DISABLED)
def view_time_logs(self):
try:
with open("time_log.csv", "r") as file:
logs = list(csv.reader(file))
if len(logs) > 1:
log_window = tk.Toplevel(self.root)
log_window.title("Time Logs")
text_area = tk.Text(log_window, height=20, width=120)
text_area.pack(padx=10, pady=10)
for log in logs[1:]:
task_name, probable_time, start_time, end_time, time_spent, time_diff = log
color = "green" if float(time_diff) < 0 else "red"
text_area.insert(tk.END, f"Task: {task_name}, Probable: {probable_time} min, Time Spent: {time_spent} min, Diff: {time_diff} min\n", color)
text_area.config(state=tk.DISABLED)
text_area.tag_config("green", foreground="green")
text_area.tag_config("red", foreground="red")
else:
messagebox.showinfo("No Logs", "No task logs found.")
except Exception as e:
messagebox.showerror("Error", f"Could not read time logs: {e}")
if __name__ == "__main__":
root = tk.Tk()
app = TaskTrackerApp(root)
root.mainloop()
6.剪贴板翻译(ClipTranslate)
你是否常因复制的文本太多而难以追踪粘贴的内容,甚至不小心丢失了重要信息?是否在遇到外语文本时,总是不得不频繁求助于翻译工具?
现在,有了这个自动化脚本,你就能轻松管理剪贴板。它不仅能监控你复制的所有文本,还能自动将其翻译成英文,让工作更加高效。
import tkinter as tk
from tkinter import ttk
import pyperclip # 需要安装Pyperclip
from deep_translator import GoogleTranslator
from langdetect import detect
def detect_and_translate(text):
try:
# 检测文本语言
detected_language = detect(text)
print(f"Detected language: {detected_language}")
if detected_language != 'en':
translated_text = GoogleTranslator(source=detected_language, target='en').translate(text)
print(f"Translated text: {translated_text}")
return translated_text
else:
print("The text is already in English.")
return text
except Exception as e:
print(f"Error: {e}")
return text
## 更新GUI,显示新复制的文本
def update_listbox():
new_item = pyperclip.paste()
new_item = detect_and_translate(new_item)
if new_item not in X:
X.append(new_item)
listbox.insert(tk.END, new_item)
listbox.insert(tk.END, "----------------------")
listbox.yview(tk.END)
root.after(1000, update_listbox)
## 检查复制的内容
def copy_to_clipboard(event):
selected_item = listbox.get(listbox.curselection())
if selected_item:
pyperclip.copy(selected_item)
X = []
root = tk.Tk()
root.title("Clipboard Manager")
root.geometry("500x500")
root.configure(bg="#f0f0f0")
frame = tk.Frame(root, bg="#f0f0f0")
frame.pack(padx=10, pady=10)
label = tk.Label(frame, text="Clipboard Contents:", bg="#f0f0f0")
label.grid(row=0, column=0)
scrollbar = tk.Scrollbar(root)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
listbox = tk.Listbox(root, width=150, height=150, yscrollcommand=scrollbar.set)
listbox.pack(pady=10)
scrollbar.config(command=listbox.yview)
update_listbox()
listbox.bind("<Double-Button-1>", copy_to_clipboard)
root.mainloop()
7.视频转GIF(Video2GIF)
对于内容创作者来说,GIF在内容表达上具有不可替代的作用。虽然视频适合分享和展示,但在文章中嵌入GIF往往更为合适。这个自动化脚本能够将视频转换成无水印的GIF,仅需几行代码即可完成。
from moviepy.editor import VideoFileClip
def convert_video_to_gif(video_path, gif_path, start_time=0, duration=None):
# 加载视频剪辑
clip = VideoFileClip(video_path)
# 如果指定了时长,则裁剪GIF的视频片段;否则使用整个视频
if duration:
clip = clip.subclip(start_time, start_time + duration)
else:
clip = clip.subclip(start_time, clip.duration)
# 将裁剪的视频片段写为GIF
clip.write_gif(gif_path)
print(f"GIF saved to {gif_path}")
video_path = "Sample_Video.mp4" # 视频文件路径
gif_path = "output.gif" #GIF保存路径
convert_video_to_gif(video_path, gif_path, start_time=0, duration=15)
8.字数统计(WordCounter)
这个自动化脚本能够追踪你每天写了多少字,还能在达到写作目标时给予鼓励。
import pynput
from pynput.keyboard import Key, Listener
from win10toast import ToastNotifier
# 初始化ToastNotifier对象
toaster = ToastNotifier()
keys = []
word_count_session = 0
word_count = 1000 # 累计写作字数
target_word_count = 1000 # 每日目标字数
def on_press(key):
global word_count_session, keys
if key == Key.space:
word_count_session += 1
elif key == Key.esc:
return False
keys.append(key)
write_file(keys)
if word_count_session >= 1000:
session_info()
def session_info():
global word_count, word_count_session
word_count += word_count_session
word_count_session = 0
if word_count > target_word_count:
# 提示消息
message = f"Congrats! You have achieved your {target_word_count} Words Daily Target"
toaster.show_toast("Counter ⏱️", message, duration=10)
def write_file(keys):
with open('log.txt', 'w') as f:
for key in keys:
if key == Key.space:
f.write(' ')
else:
k = str(key).replace("'", "")
if k[0:3] == 'Key':
pass
else:
f.write(k)
with Listener(on_press=on_press) as listener:
listener.join()
9.假数据填充(FakeFill)
对于数据科学家来说,测试模型时需要生成逼真的假数据集;对于普通人来说,填写表格时也需要随机信息。
这个Python自动化脚本能够满足这些需求,快速创建看起来真实的假数据,非常适合测试、开发和模拟用途。无论是姓名、电子邮件还是电话号码,这个工具都能高效地产出样本数据。
import streamlit as st
import pandas as pd
from mimesis import Person, Address
from mimesis.enums import Gender
from io import StringIO
# 可用数据生成器字典
generators = {
"Name": lambda: person.full_name(),
"Email": lambda: person.email(),
"Address": lambda: address.address(),
"Phone Number": lambda: person.telephone(),
"Job": lambda: person.occupation(),
}
# 生成数据的函数
def generate_data(columns, rows):
data = {col: [generators[col]() for _ in range(rows)] for col in columns}
return pd.DataFrame(data)
# Streamlit界面
st.title("Test Data Generator 📊")
# 设置侧边栏
st.sidebar.header("Data Generation Settings")
selected_columns = st.sidebar.multiselect("Select Columns:", list(generators.keys()))
num_rows = st.sidebar.number_input("Number of Rows:", min_value=1, max_value=1000, value=10)
if st.sidebar.button("Generate Data"):
if selected_columns:
person = Person() # 初始化Mimesis人物提供者
address = Address() # 初始化Mimesis地址提供者
df = generate_data(selected_columns, num_rows)
st.write("### Generated Data")
st.dataframe(df)
# 将DataFrame转换为CSV并创建下载链接
csv = df.to_csv(index=False)
st.download_button(label="Download CSV", data=csv, file_name="random_data.csv", mime="text/csv")
else:
st.warning("Please select at least one column.")
10.邮件头侦探(HeaderSpy)
电子邮件头承载着揭示邮件来源、传输路径和内容的重要元数据。虽然这些信息默认对收件人隐藏,但可以通过邮件客户端或特定工具查看。每个邮件头字段都有其特定功能,对电子邮件系统的顺畅运作起着重要作用,它们帮助验证邮件真实性,提供发送者信息透明度,并在防止垃圾邮件、验证身份和解决投递问题上发挥着重要作用。
这个自动化脚本能从邮件头中提取关键信息,助你辨别邮件是否伪造、反弹或有潜在恶意。
import email
import quopri
from email import policy
from email.parser import BytesParser
def parse_email(file_path):
with open(file_path, 'rb') as file:
msg = BytesParser(policy=policy.default).parse(file)
print("From:", msg.get("From", "N/A"))
print("To:", msg.get("To", "N/A"))
print("Subject:", msg.get("Subject", "N/A"))
print("Date:", msg.get("Date", "N/A"))
print("Message ID:", msg.get("Message-ID", "N/A"))
print("X-Mailer:", msg.get("X-Mailer", "N/A"))
# 打印附加信息
print("\n--- Additional Information ---\n")
print("SPF:", msg.get("Received-SPF", "N/A"))
print("DKIM:", msg.get("DKIM-Signature", "N/A"))
print("DMARC:", msg.get("DMARC-Filter", "N/A"))
print("SENDERIP:", msg.get("X-Sender-IP", "N/A"))
print("RETURN PATH:", msg.get("Return-Path", "N/A"))
print("Reply-To:", msg.get("Reply-To", "N/A"))
print('Authentication Results:\n', msg.get('Authentication-Results','N/A'))
print('Message ID', msg.get('Message-Id','N/A'))
def main():
email_file_path = "/content/Sample.eml" ## 邮件文件路径
parse_email(email_file_path)
if __name__ == "__main__":
main()