四個有趣且實用的Python腳本!超硬核!
在Python編程的世界中,掌握一些經(jīng)典的、實用的腳本是每個開發(fā)者進階之路上不可或缺的一步。
這里筆者與大家分享四個有趣且實用的Python腳本!
1.彩色圖像轉(zhuǎn)黑白圖像(批量操作)
該腳本展示了如何從當(dāng)前目錄下讀取所有.jpg和.png文件并將其轉(zhuǎn)換為黑白圖像。如果你想批量轉(zhuǎn)換指定目錄下的所有圖片,只需修改os.listdir('.')為你需要的目錄路徑即可。
from PIL import Image
import os
def convert_to_grayscale(image_path):
# 打開圖片
img = Image.open(image_path)
# 轉(zhuǎn)換為灰度模式(黑白)
grayscale_img = img.convert('L')
# 保存新的黑白圖像
output_filename = os.path.splitext(image_path)[0] + '_gray.png' # 添加_gray后綴以區(qū)分原圖
grayscale_img.save(output_filename)
# 遍歷當(dāng)前目錄下的所有.jpg和.png文件
for filename in os.listdir('.'):
if filename.endswith(('.jpg', '.png')):
image_path = os.path.join('.', filename)
convert_to_grayscale(image_path)
2.計算你的年齡
該腳本展示了如何計算并顯示你的年齡的年數(shù)、月數(shù)和天數(shù)。
Python 腳本:計算用戶年齡的精確年數(shù)、月數(shù)和天數(shù)
# Python 腳本:計算用戶年齡的精確年數(shù)、月數(shù)和天數(shù)
```python
import time
from calendar import isleap
# 判斷閏年函數(shù)
def is_leap_year(year):
"""
接收一個整數(shù)年份作為參數(shù),判斷該年是否為閏年并返回布爾值。
"""
return isleap(year)
# 返回指定月份天數(shù)的函數(shù)
def days_in_month(month, leap_year):
"""
接收一個整數(shù)月份(1-12)和一個布爾值(表示當(dāng)年是否為閏年),
返回該月份的天數(shù)。
"""
if month in [1, 3, 5, 7, 8, 10, 12]:
return 31
elif month in [4, 6, 9, 11]:
return 30
elif month == 2 and leap_year:
return 29
elif month == 2 and not leap_year:
return 28
# 獲取當(dāng)前時間信息
current_time = time.localtime(time.time())
# 獲取用戶輸入
name = input("請輸入您的姓名: ")
age = int(input("請輸入您的年齡: "))
# 計算用戶的出生年份
birth_year = current_time.tm_year - age
# 初始化計算總天數(shù)
total_days = 0
# 計算從出生年份到當(dāng)前年份的所有天數(shù)
for year in range(birth_year, current_time.tm_year + 1):
# 根據(jù)年份判斷是否為閏年,并累加相應(yīng)的天數(shù)
total_days += 366 if is_leap_year(year) else 365
# 計算從出生年份到當(dāng)前月份的所有額外天數(shù)
for month in range(1, current_time.tm_mon):
# 判斷對應(yīng)年份是否為閏年,獲取該月天數(shù)并累加
leap_status = is_leap_year(current_time.tm_year) if month <= current_time.tm_mon else is_leap_year(current_time.tm_year - 1)
total_days += days_in_month(month, leap_status)
# 累加當(dāng)前日期天數(shù)
total_days += current_time.tm_mday
# 輸出結(jié)果
print(f"{name} 的年齡是 {age} 年或 {current_time.tm_mon} 個月或 {total_days} 天")
3.JSON轉(zhuǎn)CSV
該腳本展示了如何從JSON文件中提取數(shù)據(jù),并將其轉(zhuǎn)換成CSV文件。
# 導(dǎo)入Python的json模塊,用于處理JSON數(shù)據(jù)
import json
# 判斷是否為腳本主入口
if __name__ == '__main__':
try:
# 讀取JSON文件,并將其內(nèi)容轉(zhuǎn)換為Python對象(這里是一個列表,其中每個元素是字典)
with open('input.json', 'r') as f:
data = json.loads(f.read())
# 初始化輸出字符串,將第一個字典的所有鍵按逗號分隔拼接成CSV表頭
output = ','.join([*data[0].keys()])
# 遍歷JSON數(shù)據(jù)中的每個字典對象
for obj in data:
# 拼接每條記錄的值,按照指定順序("Name", "age", "birthyear")與逗號分隔寫入一行
output += f'\n{obj["Name"]},{obj["age"]},{obj["birthyear"]}'
# 打開名為 'output.csv' 的文件進行寫操作,并將處理好的CSV格式數(shù)據(jù)寫入文件
with open('output.csv', 'w') as f:
f.write(output)
except Exception as ex: # 如果在執(zhí)行過程中出現(xiàn)任何異常
# 輸出錯誤信息,包含具體的異常描述
print(f'Error: {str(ex)}')
4.低電量通知
該腳本展示了如何獲取設(shè)備系統(tǒng)電池信息,然后檢查電池電量百分比是否低于30%且未連接電源。如果滿足這兩個條件,則會發(fā)送一個桌面通知提醒用戶。
import psutil
# 獲取電池信息
battery = psutil.sensors_battery()
plugged = battery.power_plugged
percent = battery.percent
# 檢查電池電量并發(fā)送通知(在電量低于30%且未插電源時)
if percent <= 30 and not plugged:
# 對于Linux環(huán)境或跨平臺通知可以使用pynotifier
try:
from pynotifier import Notification
Notification(
title="Battery Low",
description=str(percent) + "% Battery remain!!",
duration=5, # Duration in seconds
).send()
except ImportError:
print("pynotifier is not installed. Install it first.")
# 對于Windows環(huán)境,請確保已經(jīng)安裝了win10toast,并使用它來發(fā)送通知
try:
from win10toast import ToastNotifier
toaster = ToastNotifier()
toaster.show_toast(
"Battery Low",
str(percent) + "% Battery remain!!",
duration=5,
threaded=True
)
except ImportError:
print("win10toast is not installed. Install it first.")