必收藏!五个 Python 迷你项目及源码

2024-12-31 01:28:47   小编

必收藏!五个 Python 迷你项目及源码

在 Python 的世界里,通过实践项目可以快速提升编程技能。以下为您介绍五个有趣且实用的 Python 迷你项目,并附上源码,助您在编程之路上更进一步。

项目一:猜数字游戏

这是一个简单而经典的游戏。程序随机生成一个数字,玩家通过输入猜测,程序给出提示,直到猜对为止。

import random

def guess_game():
    num = random.randint(1, 100)
    guess = 0
    while guess!= num:
        guess = int(input("请输入您的猜测: "))
        if guess > num:
            print("猜大了,再试试!")
        elif guess < num:
            print("猜小了,再试试!")
    print("恭喜您,猜对了!")

项目二:文本文件统计

该项目可以统计文本文件中的字符数、单词数和行数。

def file_stats(file_path):
    with open(file_path, 'r') as file:
        content = file.read()
        char_count = len(content)
        word_count = len(content.split())
        line_count = content.count('\n') + 1
        print(f"字符数: {char_count}")
        print(f"单词数: {word_count}")
        print(f"行数: {line_count}")

项目三:简单的爬虫

通过 Python 的 requests 和 BeautifulSoup 库,抓取网页的标题和内容。

import requests
from bs4 import BeautifulSoup

def simple_web_scraper(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    title = soup.title.string
    content = soup.get_text()
    print(f"标题: {title}")
    print(f"内容: {content}")

项目四:生成随机密码

可以根据指定的长度和字符类型生成随机密码。

import random
import string

def generate_password(length=8):
    all_characters = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(random.choice(all_characters) for i in range(length))
    return password

项目五:图片转字符画

将图片转换为用字符表示的图像。

from PIL import Image

def image_to_ascii(image_path):
    image = Image.open(image_path)
    width, height = image.size
    aspect_ratio = height / width
    new_width = 80
    new_height = int(aspect_ratio * new_width)
    image = image.resize((new_width, new_height))
    pixels = image.load()
    for y in range(new_height):
        for x in range(new_width):
            r, g, b = pixels[x, y]
            gray = int(0.2989 * r + 0.5870 * g + 0.1140 * b)
            if gray > 200:
                print(' ', end='')
            elif gray > 150:
                print('.', end='')
            elif gray > 100:
                print('*', end='')
            else:
                print('#', end='')
        print()

这些迷你项目涵盖了不同的领域和应用场景,通过实践和探索,您将更深入地理解 Python 的编程思想和技巧。赶紧收藏并动手尝试吧!

TAGS: Python 编程 收藏必备 Python 迷你项目 项目代码

欢迎使用万千站长工具!

Welcome to www.zzTool.com