ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

10 个带有代码的 Python 项目

2023-07-06 17:00:46  阅读:238  来源: 互联网

标签:Python 编程 编程语言


1- URL 缩短器:

URL 缩短器是一个方便的工具,可以将较长的网站链接压缩为较短的链接。在此项目中,您将使用 Python 和 Flask(一种流行的 Web 框架)构建 URL 缩短器。通过利用 Flask 的强大功能,您将学习如何处理 HTTP 请求、生成独特的短代码以及将用户重定向到原始 URL。

fromflask import Flask, redirect, render_template, request 
import string 
import random 

app = Flask(__name__) #

存储短代码到原始 URL 映射的字典
url_mapping = {} defgenerate_short_code 


(  ): """生成随机短代码。 """    字符 = string.ascii_letters + string.digits     Short_code = '' .join(random.choice(characters) for _ in range ( 6 )) return Short_code @app.route( '/' ,methods=[ 'GET' ,
    

 
    


'POST' ] )
def home():
    ifrequest.method =='POST':
        Original_url = request.form['url']
        Short_code =generate_short_code()

        url_mapping[short_code] = Original_url

        Short_url = request.host_url + Short_code
        returnrender_template ('index.html',short_url=short_url)return

    render_template('index.html')


@app.route( '/<short_code>' )
defredirect_to_original_url (short_code):如果短代码
    url_mapping:
        original_url = url_mapping[short_code]
        返回重定向(original_url) 
    else :
        返回 “未找到短网址”。


if __name__ == '__main__' : 
    app.run(debug= True )

2.图像标题生成器:

图像字幕是深度学习的一个令人着迷的应用。在此项目中,您将使用 Python 和 TensorFlow 库创建图像标题生成器。通过结合计算机视觉和自然语言处理技术,您的程序将能够自动生成图像的描述性标题。

import tensorflow as tf 
import matplotlib.pyplot as plt 
import numpy as np 
from PIL import Image 
import os 

# 加载预训练的 InceptionV3 模型
inception_model = tf.keras.applications.InceptionV3(include_top= True , Weights= 'imagenet' ) 

# 加载分词器
tokenizer = tf.keras.preprocessing.text.Tokenizer() 
tokenizer_path = 'tokenizer.pkl'
 tokenizer = tf.keras.preprocessing.text.tokenizer_from_json(tokenizer_path)

# 定义字幕的最大序列长度(单词数)
 max_sequence_length = 20 

# 加载预训练的字幕生成模型
model_path = 'caption_generator_model.h5'
 model = tf.keras.models.load_model(model_path) 

# 加载单词到-index 和索引到单词的映射
word_to_index = tokenizer.word_index 
index_to_word = {index: word for word, index in word_to_index.items()} 

# 加载预训练的 InceptionV3 模型
inception_model = tf.keras.applications.InceptionV3(include_top = True , 权重 = 'imagenet' ) 

def  preprocess_image ( image_path): 
    """预处理图像以输入到 InceptionV3 模型。"""
     img = Image. open (image_path) 
    img = img.resize(( 299 , 299 )) img =
     np.array(img) 
    img = img / 255.0
     img = img.reshape( 1 , 299 , 299 , 3 ) 
    return img 

defgenerate_caption  ( image_path ) : """为给定图像生成标题。"""     img = preprocess_image(image_path)     features = inception_model.predict(img)     features = features.
    


, - 1 ) 
    
    start_token = tokenizer.word_index[ '<start>' ] 
    end_token = tokenizer.word_index[ '<end>' ]
    
    标题 = [] 
    input_sequence = [start_token] 
    for _ in  range (max_sequence_length): 
        sequence = np.array (input_sequence) 
        y_pred = model.predict([features,equence]) 
        y_pred = np.argmax(y_pred) 
        
        if index_to_word[y_pred] == '<end>' :
            中断
        
        caption.append(index_to_word[y_pred]) 
        input_sequence.append( y_pred) 
    
    generated_caption = ' '。加入(标题)
    return generated_caption 

# 用于生成标题的图像路径
image_path = 'example_image.jpg' 

# 为图像生成标题 Caption
 =generate_caption(image_path) 
print ( 'Generate Caption:' , Caption) 

# 显示图像
img = Image. 打开(image_path) 
plt.imshow(img) 
plt.axis( 'off' ) 
plt.show()

3.天气预报应用程序:

构建天气预报应用程序将为您提供使用 API 的宝贵经验。您将使用 Python 和 OpenWeatherMap API 获取给定位置的天气数据并将其显示给用户。该项目将涉及发出 HTTP 请求、解析 JSON 响应以及以用户友好的方式呈现数据。

import requests 
import json 

def  get_weather_data ( api_key, city ): 
    """使用 OpenWeatherMap API 获取特定城市的天气数据。"""
     base_url = "http://api.openweathermap.org/data/2.5/weather"
     params = { 
        "q" : city, 
        "appid" : api_key, 
        "units" : "metric"
     } 
    response = requests.get(base_url, params=params) 
    data = response.json()
    返回数据

def  display_weather ( data ): 
    " ”“显示天气信息。"""
    如果数据[“鳕鱼” ]!= “404”
        城市=数据[ “名称” ]
        国家=数据[ “系统” ][ “国家” ]
        温度=数据[ “主要” ][ “温度” ]
        描述=数据[ “天气” ][ 0 ][ “描述” ]
        湿度 = data[ "main" ][ "humidity" ] 
        Wind_speed = data[ "wind" ][ "speed" ] 

        print ( f" {城市}{国家}的天气:” )
        print ( f"温度: {温度} °C" ) 
        print ( f"描述: {description} " ) 
        print ( f"湿度: {humidity} %" ) 
        print ( f"风速: {wind_speed} km/h" ) 
    else : 
        print ( "未找到城市。请重试。" ) 

def  main (): 
    # 来自 OpenWeatherMap 的 API 密钥
    api_key = "YOUR_API_KEY" 

    # 从用户处获取城市名称
    city = input ("输入城市名称: " ) 

    # 获取该城市的天气数据
    Weather_data = get_weather_data(api_key, city) 

    # 显示天气信息
    display_weather(weather_data) 

if __name__ == "__main__" : 
    main()

4.音乐播放器:

使用 Python 创建音乐播放器是探索图形用户界面 (GUI) 的绝佳方法。您可以使用 Tkinter 库设计一个基本的音乐播放器,允许用户浏览其音乐库、播放歌曲、暂停、停止和调节音量。该项目将帮助您深入了解事件驱动编程和 GUI 开发。

import tkinter as tk 
import os 
from pygame import mixer 

class  MusicPlayer : 
    def  __init__ ( self, root ): 
        self.root = root 
        self.root.title( "音乐播放器" ) 
        self.root.geometry( "300x100" ) 

        # 初始化 Pygame Mixer
         Mixer.init() 

        # 创建一个变量来存储当前播放状态
        self.playing = False 

        # 创建一个变量来存储当前选择的歌曲
        self.current_song = None

        # 创建 UI 元素
        self.label = tk.Label(root, text= "Music Player" ) 
        self.label.pack() 

        self.play_button = tk.Button(root, text= "Play" , command=self.play_music ) 
        self.play_button.pack() 

        self.stop_button = tk.Button(root, text= "停止" , command=self.stop_music) 
        self.stop_button.pack() 

        self.browse_button = tk.Button(root, text= "浏览" , command=self.browse_music) 
        self.browse_button.pack() 

    def  play_music ( self ):
        如果self.current_song:
            如果 不是self.playing:
                mixer.music.load(self.current_song)
                mixer.music.play()
                self.play_button.config(text = “暂停”
                self.playing = True
            其他
                mixer.music.pause()
                self.play_button.config(text = "播放" ) 
                self.playing = False 

    def  stop_music ( self ): 
        Mixer.music.stop() 
        self.play_button.config(text= "播放" ) 
        self.playing = False 

    def  browser_music ( self ):
        self.current_song = tk.filedialog.askopenfilename(initialdir=os.getcwd(), title= "选择歌曲" , 
                                                         filetypes=(( "音频文件" , "*.mp3" ), ( "所有文件" , "*. *" ))) 
        self.label.config(text=os.path.basename(self.current_song)) 

if __name__ == '__main__' : 
    root = tk.Tk() 
    music_player = MusicPlayer(root) 
    root.mainloop()

5. 数独求解器:

解决数独难题是一项经典的编程挑战,可以测试您解决问题的能力。在此项目中,您将使用 Python 和回溯算法构建数独求解器。您将学习如何表示谜题、实现求解器以及使用图形界面可视化解决方案。

def  is_valid ( board, row, col, num ): 
    # 检查该数字是否已经存在于该行
    for i in  range ( 9 ): 
        if board[row][i] == num: 
            return  False 

    # 检查该数字是否已经存在存在于列中
    for i in  range ( 9 ): 
        if board[i][col] == num: 
            return  False 

    # 检查该数字是否已存在于 3x3 网格中
    start_row = (row // 3 ) * 3
     start_col = (列 // 3 ) * 3
    i 范围( 3 ) 中:
        for j 范围( 3 ) 中:
            if board[start_row + i][start_col + j] == num: return 
                False  return 

    True  defsolve_sudoku 

(  board ) : for row in range ( 9 ): for col in range ( 9 ): if board[row][col] == 0 : for num in range ( 1 , 10
     
         
            
                 ): 
                    if is_valid(board, row, col, num): 
                        board[row][col] = num 

                        ifsolve_sudoku (board): 
                            return  True

                         board[row][col] = 0 

                return  False 

    return  True 

def  print_board ( board ): 
    for row in  range ( 9 ): 
        for col in  range ( 9 ): 
            print (board[row][col], end= " " ) 
        print () 

# 数独板示例(0 代表空单元格)
棋盘 = [ 
    [ 5 , 3 , 0 , 0 , 7 , 0 , 0 , 0 , 0 ], 
    [ 6 , 0 , 0 , 1 , 9 , 5 , 0 , 0 , 0 ] , 
    [ 0 , 9 , 8 , 0 , 0 , 0 , 0 , 6 , 0 ],
    [ 8,0,0,0,6,0,0,0,3 ] , [ 4,0,0,8,0,3,0,0,1 ] , [ 7,0,0,0,2 _ _ _ _ _ _ _ _ _     _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _     _ _ _ _ _ _ _ _ _ _ , 0 , 0 , 0 , 6 ],     [


0 , 6 , 0 , 0 , 0 , 0 , 2 , 8 , 0 ], 
    [ 0 , 0 , 0 , 4 , 1 , 9 , 0 , 0 , 5 ], 
    [ 0 , 0 , 0 , 0 , 8 , 0 , 0 , 7 , 9 ] 
]

如果solve_sudoku(board): 
    print ( "数独已解决:" ) 
    print_board(board) 
else : 
    print ( "给定的数独板不存在解。" )

6. 使用 BeautifulSoup 进行网页抓取:

网络抓取涉及从网站提取数据,它是各个领域的一项宝贵技能。在此项目中,您将使用 Python 和 BeautifulSoup 库从您选择的网站中抓取数据。您将学习如何导航 HTML 结构、提取特定信息并将其保存到文件或数据库中。

import requests 
from bs4 import BeautifulSoup 

# 向网站发送 GET 请求
url = 'https://example.com'
 response = requests.get(url) 

# 创建一个 BeautifulSoup 对象
soup = BeautifulSoup(response.text, 'html.parser ' ) 

# 从网页中查找并提取特定元素
title = soup.title.text 
paragraphs = soup.find_all( 'p' ) 

# 打印提取的数据
print ( 'Title:' , title) 
print ( 'Paragraphs:' ) 
for段落中的p 
    打印(p.文本)

7. 聊天机器人:

构建聊天机器人是一个令人兴奋的项目,它结合了自然语言处理和机器学习。您可以使用 Python 和 NLTK 或 spaCy 等库来创建可以理解用户查询并提供相关响应的聊天机器人。该项目将向您介绍文本预处理、意图识别和响应生成等技术。

import random 

# 示例响应列表
messages = [ 
    "Hello!" 
    “你好!” 
    “你好!” 
    “很高兴认识你!” 
    “我能为您提供什么帮助吗?” 
    “我是来帮忙的!” 
    “今天怎么样?” , 
] 

def  get_random_response (): 
    """从样本响应列表中返回一个随机响应。""" 
    return random.choice(responses) 

def  chat (): 
    """处理聊天机器人对话的主要函数。
    

     True : 
        user_input = input ( "User: " ) 
        
        # 检查用户是否想要结束对话
        if user_input.lower() == "bye" : 
            print ( "Chatbot: Goodbye!" ) 
            break 
        
        # 生成并打印随机响应
        print ( "Chatbot: " + get_random_response()) 

if __name__ == "__main__" : 
    print ( "Chatbot: 您好!需要什么帮助吗?" ) 
    chat()

8.密码管理器:

密码管理器是安全存储和管理密码的有用工具。在此项目中,您将使用 Python 和加密库开发密码管理器。您的程序将允许用户存储其密码、生成强密码并加密数据以确保安全。

import hashlib 
import getpasspasswords 

= {} 

def  get_hashed_pa​​ssword ( password ): 
    """生成 SHA-256 哈希密码。"""
     sha256_hash = hashlib.sha256() 
    sha256_hash.update(password.encode( 'utf-8' )) 
    return sha256_hash.hexdigest() 

def  create_password (): 
    """创建一个新的密码条目。"""
     website = input ( "输入网站:" ) 
    username = input ( "输入您的用户名:" ) 
    password = getpass.getpass( "请输入您的密码:") 
    hashed_pa​​ssword = get_hashed_pa​​ssword(password) 
    passwords[website] = (username, hashed_pa​​ssword) 
    print ( "密码创建成功。" ) 

defretrieve_password  (): """从密码管理器检索
    密码。"""
     website = input ( "输入网站: " )
    如果网站密码
:         username, hashed_pa​​ssword = passwords[网站]
        密码 = getpass.getpass( "输入您的密码: " ) 
        if hashed_pa​​ssword == get_hashed_pa​​ssword(password):
            print ( f"用户名:{username} " )
             print ( f"密码: {password} " )
         else :
             print ( "密码不正确。" )
     else :
         print ( "在密码管理器中找不到网站。" )

 def  main ():
     while  True :
         print ( "1. 创建新密码" )
         print ( "2. 找回密码" )
         print ( "3. 退出" )
        choice = input ( "输入您的选择(1-3):” )

        if choice == "1" : 
            create_password() 
        elif choice == "2" : 
            retrieve_password() 
        elif choice == "3" : 
            break 
        else : 
            print ( "无效选​​择。请重试。" ) 

if __name__ == " __main__" :
    主函数()

9. 股价分析器:

分析股票价格对于投资者和交易者至关重要。在此项目中,您将使用 Python 和 Yahoo Finance API 创建股票价格分析器。您将获取历史股票数据,计算各种财务指标,并使用图表可视化结果。该项目将提高您的数据分析和可视化技能。

import yfinance as yf 
import matplotlib.pyplot as plt 

def  recognize_stock ( symbol, start_date, end_date ): 
    # 从雅虎财经获取股票数据
    stock_data = yf.download(symbol, start=start_date, end=end_date) 

    # 计算每日收益
    stock_data [ 'Daily Return' ] = stock_data[ 'Close' ].pct_change() 

    # 绘制收盘价和每日收益
    plt.figure(figsize=( 10 , 5 )) 
    plt.subplot( 2 , 1 , 1 )
    plt.plot(stock_data[ '收盘' ]) 
    plt.title( '股票价格' ) 
    plt.ylabel( '价格' ) 

    plt.subplot( 2 , 1 , 2 ) 
    plt.plot(stock_data[ '每日收益' ]) 
    plt.title( 'Daily Returns' ) 
    plt.ylabel( 'Return' ) 

    plt.tight_layout() 
    plt.show() 

# 使用示例
symbol = 'AAPL'   # 股票代码(例如 Apple Inc.)
) start_date = '2022-01-01'   # 分析的开始日期
end_date = '2022-12-31'  # 分析的结束日期

analyze_stock(symbol, start_date, end_date)

10.自动电子邮件发送器:

自动执行重复性任务是 Python 的常见用例。在此项目中,您将构建一个自动电子邮件发送器,它可以向收件人列表发送个性化电子邮件。您将使用 Python 的内置电子邮件库来撰写和发送电子邮件

以编程方式。该项目将深入了解电子邮件协议、处理附件和批量发送电子邮件。

import smtplib 
from email.mime.multipart import MIMEMultipart 
from email.mime.text import MIMEText 

def  send_email ( sender_email, sender_password,recipient_email, subject, message ): 
    # 创建多部分消息
    msg = MIMEMultipart() 
    msg​​[ 'From' ] = sender_email 
    msg[ 'To' ] =收件人_电子邮件
    msg[ 'Subject' ] = subject 

    # 添加邮件正文
    msg.attach(MIMEText(message, 'plain' )) 

    # 设置 SMTP 服务器
    smtp_server ='smtp.gmail.com'
     smtp_port = 587 

    try : 
        # 启动 SMTP 服务器连接
        server = smtplib.SMTP(smtp_server, smtp_port) 
        server.starttls() 

        # 登录电子邮件帐户
        server.login(sender_email, sender_password) 

        # 发送email
         server.sendmail(sender_email,recipient_email,msg.as_string()) 

        print ( '电子邮件发送成功!' ) 
    except Exception as e: 
        print ( '发送电子邮件时发生错误:' , str (e)) 
    finally : 
        #终止 SMTP 服务器连接
        server.quit() 

# 用法示例
sender_email = 'your-email@gmail.com'   # 您的 Gmail 电子邮件地址
sender_password = 'your-password'   # 您的 Gmail 密码
收件人_email = 'recipient-email@example.com'   # 的电子邮件地址收件人
主题 = '自动电子邮件'   # 电子邮件主题
消息 = '您好,这是一封自动电子邮件。'   # 电子邮件消息

send_email(sender_email, sender_password,recipient_email, subject, message)

结论
使用代码处理 Python 项目是提高编程技能的有效方法。在这篇博文中,我们探讨了十个不同的项目,涵盖网络开发、数据分析、机器学习和自动化等领域。通过完成这些项目,您将获得实践经验并对 Python 及其库有更深入的了解。因此,选择一个您感兴趣的项目,深入研究代码,并在使用 Python 构建实际应用程序时释放您的创造力。

标签:Python,编程,编程语言
来源:

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有