精选Python小项目代码
1. 猜字游戏
功能:通过字母猜测隐藏的水果单词
import random
def guess_word_game():
words = ["apple", "banana", "cherry"]
target = random.choice(words)
guessed = []
attempts = 6
print("欢迎来到猜字游戏!")
while attempts > 0:
guess = input("猜一个字母: ").lower()
if guess in guessed:
print("已猜过该字母")
continue
guessed.append(guess)
if guess in target:
display = " ".join([c if c in guessed else "_" for c in target])
print(display)
if "_" not in display:
print("胜利!")
break
else:
attempts -= 1
if attempts == 0:
print(f"失败!答案是{target}")
if __name__ == "__main__":
guess_word_game()
2. 加密解密工具
功能:实现凯撒密码加密与解密
def encrypt(text, shift):
encrypted = ""
for char in text:
if char.isalpha():
base = ord('a') if char.islower() else ord('A')
encrypted += chr((ord(char)-base + shift)%26 + base)
else:
encrypted += char
return encrypted
def decrypt(text, shift):
return encrypt(text, -shift)
# 示例
original = "Hello"
encrypted = encrypt(original, 3) # 输出 Khoor
decrypted = decrypt(encrypted, 3) # 还原 Hello
3. 天气查询应用
功能:通过爬虫获取实时天气
import requests
from bs4 import BeautifulSoup
def get_weather(city):
url = f"https://www.google.com/search?q={city}+weather"
headers = {'User-Agent': 'Mozilla/5.0'}
res = requests.get(url, headers=headers)
soup = BeautifulSoup(res.text, 'html.parser')
location = soup.find("div", {"id": "wob_loc"}).text
temp = soup.find("span", {"id": "wob_tm"}).text
print(f"{location}: {temp}°C")
get_weather("北京") # 示例输出:北京市天气: 25°C
4. 人脸检测工具
功能:识别并裁剪图像中的人脸
import cv2
def detect_faces(image_path):
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
img = cv2.imread(image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2)
cv2.imwrite(f"face_{x}.jpg", img[y:y+h, x:x+w])
cv2.imshow('Detected Faces', img)
cv2.waitKey(0)
detect_faces("group_photo.jpg")
5. 倒计时器
功能:实现终端倒计时
import time
def countdown(seconds):
while seconds:
mins, secs = divmod(seconds, 60)
print(f"{mins:02d}:{secs:02d}", end="\r")
time.sleep(1)
seconds -= 1
print("时间到!")
countdown(60) # 60秒倒计时
6. URL短链生成器
功能:使用API生成短链接
import pyshorteners
def shorten_url(url):
s = pyshorteners.Shortener()
return s.tinyurl.short(url)
print(shorten_url("https://www.example.com"))
# 输出类似 https://tinyurl.com/abc123
项目扩展建议:
-
代码优化方向:
- 为GUI项目添加异常处理(如闹钟的非法输入检测)1
- 使用多线程优化阻塞操作(如倒计时器的实时输入响应)3
-
依赖管理:
- 安装必要库:
pip install opencv-python pyttsx3 pyshorteners
- 安装必要库:
-
学习路径:
- 新手:从猜字游戏/倒计时器开始
- 进阶:尝试人脸检测/网络爬虫项目