当前位置: 首页 > news >正文

精选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

项目扩展建议:

  1. 代码优化方向

    • 为GUI项目添加异常处理(如闹钟的非法输入检测)1
    • 使用多线程优化阻塞操作(如倒计时器的实时输入响应)3
  2. 依赖管理

    • 安装必要库:pip install opencv-python pyttsx3 pyshorteners
  3. 学习路径

    • 新手:从猜字游戏/倒计时器开始
    • 进阶:尝试人脸检测/网络爬虫项目

相关文章:

  • 【前端框架】深入探讨 Vue 3 组件生命周期的变化和最佳实践
  • 卓越设计彰显品质:福特中国“烈马宇宙”项目展示高质量标准
  • linux--关于GCC、动态库静态库
  • kubectl exec 实现的原理
  • 【SQL技术】不同数据库引擎 SQL 优化方案剖析
  • 30天自制操作系统第一天(1)
  • 微信小程序性能优化
  • 寒假第三周周报
  • 基于JAVA的幼儿园管理系统的设计与实现源码(springboot+vue+mysql)
  • [创业之路-307]:如何解读公司的业绩?它与股价变化的关系?
  • c++中std::thread构造函数的注意事项
  • 【Python】Python入门基础——环境搭建
  • 数据库系统原理——第十章数据恢复技术复习题
  • 学习总结三十四
  • Ubuntu20.04部署stable-diffusion-webui环境小记
  • 题海拾贝:英语作文(map)
  • Selenium定位元素的方法及其语法
  • ubuntu20.04连接airpods pro2
  • LeetCode热题100- 缺失的第一个正数【JavaScript讲解】
  • SpringMVC的工作原理
  • 福州一宋代古墓被指沦为露天厕所,仓山区博物馆:已设置围挡
  • 贵州省委军民融合发展委员会办公室副主任李刚接受审查调查
  • 雷军内部演讲回应质疑:在不服输、打不倒方面,没人比我们更有耐心
  • 泽连斯基已离开土耳其安卡拉
  • 上海市税务局回应刘晓庆被举报涉嫌偷漏税:正依法依规办理
  • 泽连斯基:乌代表团已启程,谈判可能于今晚或明天举行