① 前言

  • Python 丰富的开发生态是它的一大优势,各种第三方库、框架和代码,都是前人造好的“轮子”,能够完成很多操作,让开发事半功倍。
  • 本文分享 22 个通过 Python 构建的项目,以此来学习 Python 编程,这些例子都很简单实用,非常适合初学者用来练习。大家也可尝试根据项目的目的及提示,自己构建解决方法,提高编程水平。

② 骰子模拟器

  • 目的:创建一个程序来模拟掷骰子。
  • 提示:当用户询问时,使用 random 模块生成一个 1 到 6 之间的数字。
import random;
while int(input('Press 1 to roll the dice or Ѳ to exit:ln')): print(random.randint(1,6))
Press 1 to roll the diceor 0 to exit
1
4

③ 石头剪刀布游戏

  • 目标:创建一个命令行游戏,游戏者可以在石头、剪刀和布之间进行选择,与计算机 PK。如果游戏者赢了,得分就会添加,直到结束游戏时,最终的分数会展示给游戏者。
  • 提示:接收游戏者的选择,并且与计算机的选择进行比较,计算机的选择是从选择列表中随机选取的,如果游戏者获胜,则增加 1 分。
import random
choices = ["Rock", "Paper", "Scissors"]
computer = random.choice(choices)
player = False
cpu_score = 0
player_score = 0
while True:player = input("Rock, Paper or  Scissors?").capitalize()# 判断游戏者和电脑的选择if player == computer:print("Tie!")elif player == "Rock":if computer == "Paper":print("You lose!", computer, "covers", player)cpu_score+=1else:print("You win!", player, "smashes", computer)player_score+=1elif player == "Paper":if computer == "Scissors":print("You lose!", computer, "cut", player)cpu_score+=1else:print("You win!", player, "covers", computer)player_score+=1elif player == "Scissors":if computer == "Rock":print("You lose...", computer, "smashes", player)cpu_score+=1else:print("You win!", player, "cut", computer)player_score+=1elif player=='E':print("Final Scores:")print(f"CPU:{cpu_score}")print(f"Plaer:{player_score}")breakelse:print("That's not a valid play. Check your spelling!")computer = random.choice(choices)

④ 随机密码生成器

  • 目标:创建一个程序,可指定密码长度,生成一串随机密码。
  • 提示:创建一个数字+大写字母+小写字母+特殊字符的字符串,根据设定的密码长度随机生成一串密码。
import random
passlen = int(input("enter the length of password"))
s = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKMNOPQRSTUVWXYZ!a#$%&*()?"
p = "".join(random.sample(s,passlen))
print(p)
-------------------------------------------------
enter the length of password
6
Za1gB0

⑤ 句子生成器

  • 目的:通过用户提供的输入,来生成随机且唯一的句子。
  • 提示:以用户输入的名词、代词、形容词等作为输入,然后将所有数据添加到句子中,并将其组合返回。
color = input("Enter a color: ")
pluralNoun = input("Enter a plural noun: " )
celebrity = input("Enter a celebrity: " )
print("Roses are", color)
print(pluralNoun + " are blue")
print("I love",celebrity)
--------------------------------------------
Red
Teeth
RDJ
Roses are red. teeth are blue. I Love RDJ

⑥ 猜数字游戏

  • 目的:在这个游戏中,任务是创建一个脚本,能够在一个范围内生成一个随机数。如果用户在三次机会中猜对了数字,那么用户赢得游戏,否则用户输。
  • 提示:生成一个随机数,然后使用循环给用户三次猜测机会,根据用户的猜测打印最终的结果。
import random
number = random.randint(1,10)
for i in range(ѳ,3):user = int(input("guess the number"))if user = number:print("Hurray!!")print("you guessed the number right it's [number]")breakelif user>number :print("Your guess is too high")elif user<number :print("Your guess is too low.")
else:print("Nice Try!, but the number is number]")

⑦ 故事生成器

  • 目的:每次用户运行程序时,都会生成一个随机的故事。
  • 提示:random 模块可以用来选择故事的随机部分,内容来自每个列表里。
import random
when = ['A few years ago', 'Yesterday', 'Last night', 'A long time ago','On 20th Jan']
who = ['a rabbit', 'an e lephant', 'a mouse', 'a turtle', 'a cat']
name =['Ali', 'Miriam', 'daniel', 'Hoouk', 'Starwalker']
residence = ['Barcelona', 'India', 'Germany', 'Venice', 'England']
went = ['cinema', 'university', 'seminar', 'school', 'laundry']
happened = ['made a lot of friends', 'Eats a burger', 'found a secret key', 'solved a mistery', 'wrote a book']
print(random.choice(when) + ',' + random.choice(who) + ' that lived in' + random.choice( residence) + ',went to the' + random.choice(went) + ' and ' + random.choice(happened))
----------------------OUTPUT-----------------------------------
A long time ago, a cat that lived in England, went to the seminar and solved a mistery

⑧ 邮件地址切片器

  • 目的:编写一个 Python 脚本,可以从邮件地址中获取用户名和域名。
  • 提示:使用 @ 作为分隔符,将地址分为分为两个字符串。
# Get the user's email address
email = input("what is your email address 7: ").strip()
# slice out the user name
user_name = email[:email.index("@")]
# Slice out the domain name
domain_name = email[:email. index("a")+1:]
# Format message
res = f"Your username is' user name]' and your domain name is '{domain name}'"
# Display the result message
print(res)
-----------------------OUTPUT-----------------------------
what is your email address?: karl31@gmail. com
Your username is "karl31" and your domain name is "gmail.com"

⑨ 自动发送邮件

  • 目的:编写一个 Python 脚本,可以使用这个脚本发送电子邮件。
  • 提示:email 库可用于发送电子邮件。
import smtplib
from email.message import EmailMessage
email = EmailMessage() ## Creating a object for EmailMessage
email['from'] = 'xyz name'   ## Person who is sending
email['to'] = 'xyz id'       ## Whom we are sending
email['subject'] = 'xyz subject'  ## Subject of email
email.set_content("Xyz content of email") ## content of email
with smtlib.SMTP(host='smtp.gmail.com',port=587)as smtp:
## sending request to server smtp.ehlo()          ## server object
smtp.starttls()      ## used to send data between server and client
smtp.login("email_id","Password") ## login id and password of gmail
smtp.send_message(email)   ## Sending email
print("email send")    ## Printing success message

⑩ 缩写词

  • 目的:编写一个 Python 脚本,从给定的句子生成一个缩写词。
  • 提示:可以通过拆分和索引来获取第一个单词,然后将其组合。

⑪ 文字冒险游戏

  • 目的:编写一个有趣的 Python 脚本,通过为路径选择不同的选项让用户进行有趣的冒险。

⑫ Hangman

  • 目的:创建一个简单的命令行 hangman 游戏。
  • 提示:创建一个密码词的列表并随机选择一个单词。现在将每个单词用下划线“”表示,给用户提供猜单词的机会,如果用户猜对了单词,则将“”用单词替换。
import time
import random
name = input("What is your name? ")
print ("Hello, " + name, "Time to play hangman!")
time.sleep(1)
print ("Start guessing...\n")
time.sleep(0.5)
## A List Of Secret Words
words = ['python','programming','treasure','creative','medium','horror']
word = random.choice(words)
guesses = ''
turns = 5
while turns > 0:         failed = 0             for char in word:      if char in guesses:    print (char,end="")    else:print ("_",end=""),     failed += 1    if failed == 0:        print ("\nYou won") break              guess = input("\nguess a character:") guesses += guess                    if guess not in word:  turns -= 1        print("\nWrong")    print("\nYou have", + turns, 'more guesses') if turns == 0:           print ("\nYou Lose")

⑬ 闹钟

  • 目的:编写一个创建闹钟的 Python 脚本。
  • 提示:可以使用 date-time 模块创建闹钟,以及 playsound 库播放声音。
from datetime import datetime
from playsound import playsound
alarm_time = input("Enter the time of alarm to be set:HH:MM:SS\n")
alarm_hour = alarm_time[0:2]
alarm_minute = alarm_time[3:5]
alarm_seconds = alarm_time[6:8]
alarm_period = alarm_time[9:11].upper()
print("Setting up alarm..")
while True:now = datetime.now()current_hour = now.strftime("%I")current_minute = now.strftime("%M")current_seconds = now.strftime("%S")current_period = now.strftime("%p")if(alarm_period == current_period):if(alarm_hour == current_hour):if(alarm_minute == current_minute):if(alarm_seconds == current_seconds):print("Wake Up!")playsound('audio.mp3') ## download the alarm sound from linkbreak

⑭ 有声读物

  • 目的:编写一个 Python 脚本,用于将 pdf 文件转换为有声读物。
  • 提示:借助 pyttsx3 库将文本转换为语音。
  • 安装:pyttsx3,PyPDF2。

⑮ 天气应用

  • 目的:编写一个 Python 脚本,接收城市名称并使用爬虫获取该城市的天气信息。
  • 提示:你可以使用 Beautifulsoup 和 requests 库直接从谷歌主页爬取数据。
  • 安装:requests,BeautifulSoup。
from bs4 import BeautifulSoup
import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}def weather(city):city=city.replace(" ","+")res = requests.get(f'https://www.google.com/search?q={city}&oq={city}&aqs=chrome.0.35i39l2j0l4j46j69i60.6128j1j7&sourceid=chrome&ie=UTF-8',headers=headers)print("Searching in google......\n")soup = BeautifulSoup(res.text,'html.parser')   location = soup.select('#wob_loc')[0].getText().strip()  time = soup.select('#wob_dts')[0].getText().strip()       info = soup.select('#wob_dc')[0].getText().strip() weather = soup.select('#wob_tm')[0].getText().strip()print(location)print(time)print(info)print(weather+"°C") print("enter the city name")
city = input()
city = city + " weather"
weather(city)

⑯ 人脸检测

  • 目的:编写一个 Python 脚本,可以检测图像中的人脸,并将所有的人脸保存在一个文件夹中。
  • 提示:可以使用 haar 级联分类器对人脸进行检测,它返回的人脸坐标信息,可以保存在一个文件中。
  • 安装:OpenCV。
  • 下载:haarcascade_frontalface_default.xml。
import cv2
# Load the cascade
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Read the input image
img = cv2.imread('images/img0.jpg')
# Convert into grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect faces
faces = face_cascade.detectMultiScale(gray, 1.3, 4)
# Draw rectangle around the faces
for (x, y, w, h) in faces:cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)crop_face = img[y:y + h, x:x + w]  cv2.imwrite(str(w) + str(h) + '_faces.jpg', crop_face)
# Display the output
cv2.imshow('img', img)
cv2.imshow("imgcropped",crop_face)
cv2.waitKey()

⑰ 提醒应用

  • 目的:创建一个提醒应用程序,在特定的时间提醒你做一些事情(桌面通知)。
  • 提示:Time 模块可以用来跟踪提醒时间,toastnotifier 库可以用来显示桌面通知。
  • 安装:win10toast。
from win10toast import ToastNotifier
import time
toaster = ToastNotifier()
try:print("Title of reminder")header = input()print("Message of reminder")text = input()print("In how many minutes?")time_min = input()time_min=float(time_min)
except:header = input("Title of reminder\n")text = input("Message of remindar\n")time_min=float(input("In how many minutes?\n"))
time_min = time_min * 60
print("Setting up reminder..")
time.sleep(2)
print("all set!")
time.sleep(time_min)
toaster.show_toast(f"{header}",
f"{text}",
duration=10,
threaded=True)
while toaster.notification_active(): time.sleep(0.005)

⑱ 维基百科文章摘要

  • 目的:使用一种简单的方法从用户提供的文章链接中生成摘要。
  • 提示:你可以使用爬虫获取文章数据,通过提取生成摘要。
from bs4 import BeautifulSoup
import re
import requests
import heapq
from nltk.tokenize import sent_tokenize,word_tokenize
from nltk.corpus import stopwordsurl = str(input("Paste the url"\n"))
num = int(input("Enter the Number of Sentence you want in the summary"))
num = int(num)
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
#url = str(input("Paste the url......."))
res = requests.get(url,headers=headers)
summary = ""
soup = BeautifulSoup(res.text,'html.parser')
content = soup.findAll("p")
for text in content:summary +=text.text
def clean(text):text = re.sub(r"\[[0-9]*\]"," ",text)text = text.lower()text = re.sub(r'\s+'," ",text)text = re.sub(r","," ",text)return text
summary = clean(summary)print("Getting the data......\n")##Tokenixing
sent_tokens = sent_tokenize(summary)summary = re.sub(r"[^a-zA-z]"," ",summary)
word_tokens = word_tokenize(summary)
## Removing Stop wordsword_frequency = {}
stopwords =  set(stopwords.words("english"))for word in word_tokens:if word not in stopwords:if word not in word_frequency.keys():word_frequency[word]=1else:word_frequency[word] +=1
maximum_frequency = max(word_frequency.values())
print(maximum_frequency)
for word in word_frequency.keys():word_frequency[word] = (word_frequency[word]/maximum_frequency)
print(word_frequency)
sentences_score = {}
for sentence in sent_tokens:for word in word_tokenize(sentence):if word in word_frequency.keys():if (len(sentence.split(" "))) <30:if sentence not in sentences_score.keys():sentences_score[sentence] = word_frequency[word]else:sentences_score[sentence] += word_frequency[word]print(max(sentences_score.values()))
def get_key(val): for key, value in sentences_score.items(): if val == value: return key
key = get_key(max(sentences_score.values()))
print(key+"\n")
print(sentences_score)
summary = heapq.nlargest(num,sentences_score,key=sentences_score.get)
print(" ".join(summary))
summary = " ".join(summary)

⑲ 获取谷歌搜索结果

  • 目的:创建一个脚本,可以根据查询条件从谷歌搜索获取数据。
from bs4 import BeautifulSoup
import requestsheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
def google(query):query = query.replace(" ","+")try:url = f'https://www.google.com/search?q={query}&oq={query}&aqs=chrome..69i57j46j69i59j35i39j0j46j0l2.4948j0j7&sourceid=chrome&ie=UTF-8'res = requests.get(url,headers=headers)soup = BeautifulSoup(res.text,'html.parser')except:print("Make sure you have a internet connection")try:try:ans = soup.select('.RqBzHd')[0].getText().strip()except:try:title=soup.select('.AZCkJd')[0].getText().strip()try:ans=soup.select('.e24Kjd')[0].getText().strip()except:ans=""ans=f'{title}\n{ans}'except:try:ans=soup.select('.hgKElc')[0].getText().strip()except:ans=soup.select('.kno-rdesc span')[0].getText().strip()except:ans = "can't find on google"return ansresult = google(str(input("Query\n")))
print(result)

⑳ 货币换算器

  • 目的:编写一个 Python 脚本,可以将一种货币转换为其他用户选择的货币。
  • 提示:使用 Python 中的 API,或者通过 forex-python 模块来获取实时的货币汇率。
  • 安装:forex-python。
from forex_python.converter import CurrencyRates
c = CurrencyRates()
amount = int(input(" Enter The Amount You Want To Convert\n"))
from currency = input("Fromn\n").upper()
to_currency = input("To\n").upper()
print(from_currency, "To", to_ currency, amount)
result = c.convert(from currency, to_currency, amount)
print(result)

㉑ 键盘记录器

  • 目的:编写一个 Python 脚本,将用户按下的所有键保存在一个文本文件中。
  • 提示:pynput 是 Python 中的一个库,用于控制键盘和鼠标的移动,它也可以用于制作键盘记录器。简单地读取用户按下的键,并在一定数量的键后将它们保存在一个文本文件中。
from pynput.keyboard import Key, Controller,Listener
import time
keyboard = Controller()keys=[]
def on_press(key):global keys#keys.append(str(key).replace("'",""))string = str(key).replace("'","")keys.append(string)main_string = "".join(keys)print(main_string)if len(main_string)>15:with open('keys.txt', 'a') as f:f.write(main_string)   keys= []
def on_release(key):if key == Key.esc:return Falsewith listener(on_press=on_press,on_release=on_release) as listener:listener.join()

㉒ 文章朗读器

  • 目的:编写一个 Python 脚本,自动从提供的链接读取文章。
import pyttsx3
import requests
from bs4 import BeautifulSoup
url = str(input("Paste article url\n"))def content(url):res = requests.get(url)soup = BeautifulSoup(res.text,'html.parser')articles = []for i in range(len(soup.select('.p'))):article = soup.select('.p')[i].getText().strip()articles.append(article)contents = " ".join(articles)return contents
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)def speak(audio):engine.say(audio)engine.runAndWait()contents = content(url)
## print(contents)      ## In case you want to see the content#engine.save_to_file
#engine.runAndWait() ## In case if you want to save the article as a audio file

㉓ 短网址生成器

  • 目的:编写一个 Python 脚本,使用API缩短给定的 URL。
from __future__ import with_statement
import contextlib
try:from urllib.parse import urlencode
except ImportError:from urllib import urlencode
try:from urllib.request import urlopen
except ImportError:from urllib2 import urlopen
import sysdef make_tiny(url):request_url = ('http://tinyurl.com/api-create.php?' + urlencode({'url':url}))with contextlib.closing(urlopen(request_url)) as response:return response.read().decode('utf-8')def main():for tinyurl in map(make_tiny, sys.argv[1:]):print(tinyurl)if __name__ == '__main__':main()
-----------------------------OUTPUT------------------------
python url_shortener.py https://www.wikipedia.org/
https://tinyurl.com/buf3qt3

㉔ 总结

  • 项目中有些需要适当调整,比如自动发送邮件,可以选择使用QQ邮箱;查询天气信息也可使用国内一些免费的API;维基百科可以对应百度百科;谷歌搜索可以对应百度搜索等。

Python之值得学习练手的22个迷你程序(附代码)相关推荐

  1. 值得学习练手的22个Python迷你程序(附代码)

    来源/法纳斯特 Python丰富的开发生态是它的一大优势,各种第三方库.框架和代码,都是前人造好的"轮子",能够完成很多操作,让你的开发事半功倍. 下面就给大家介绍22个通过Pyt ...

  2. 学习练手的22个Python迷你程序

    ① 骰子模拟器 目的:创建一个程序来模拟掷骰子. 提示:当用户询问时,使用random模块生成一个1到6之间的数字. ② 石头剪刀布游戏 目标:创建一个命令行游戏,游戏者可以在石头.剪刀和布之间进行选 ...

  3. 为何别人实操很强?因为他用这70个Python项目学习练手!它值得你收藏落灰!

    [此文章转自乐字节] 前言: 不管学习哪门语言都希望能做出实际的东西来,这个实际的东西当然就是项目啦,不用多说大家都知道学编程语言一定要做项目才行. 这里整理了70个Python实战项目列表,都有完整 ...

  4. 为何别人实操很强?因为他用这70个Python项目学习练手,值得你收藏落灰

    前言: 不管学习哪门语言都希望能做出实际的东西来,这个实际的东西当然就是项目啦,不用多说大家都知道学编程语言一定要做项目才行. 这里整理了70个Python实战项目列表,都有完整且详细的教程,你可以从 ...

  5. python新手项目-推荐:一个适合于Python新手的入门练手项目

    原标题:推荐:一个适合于Python新手的入门练手项目 随着人工智能的兴起,国内掀起了一股Python学习热潮,入门级编程语言,大多选择Python,有经验的程序员,也开始学习Python,正所谓是人 ...

  6. 给python初学者的最好练手项目-适合初学者练手的 10 个 有趣Python项目

    Python Python开发 Python语言 适合初学者练手的 10 个 有趣Python项目 想成为一个优秀的开发者,没有捷径可走,势必要花费大量时间在键盘后. 而不断地进行各种小项目开发,可以 ...

  7. Python基于深度学习的手写数字识别

    Python基于深度学习的手写数字识别 1.代码的功能和运行方法 2. 网络设计 3.训练方法 4.实验结果分析 5.结论 1.代码的功能和运行方法 代码可以实现任意数字0-9的识别,只需要将图片载入 ...

  8. 我用Python爬取了难下载的电子教材(内附代码)

    我用Python爬取了难下载的电子教材(内附代码) 第一次在CSDN上面分享经历,有点激动.本大二狗最近这段时间去不了学校又想看教材,不巧学习通上面的部分内容老师设置了不可下载啊.好在最近学习了一点P ...

  9. python头像转卡通_人工智能:一款图像转卡通的 Python 项目,超级值得你练手

    大家好,我是章鱼猫. 今天给大家推荐的开源项目,我感觉对于想学习 Python,想学习 tensorflow ,pytorch 的同学来讲,真的非常不错,是一个非常值得大家学习和练手的一个开源项目. ...

最新文章

  1. 抗击疫情!阿里云为加速新药疫苗研发提供免费AI算力
  2. 对 ResNet 本质的一些思考
  3. 【转】修改版WinXP集体歇业避免遭遇调查
  4. 好程序员大数据独家解析-hadoop五大节点
  5. ROS与Arduino学习(六)Logging日志
  6. nginx 1.16 配置反向代理,http,https,ssl
  7. 什么样的程序猿,最容易被鄙视?
  8. java的一些课程设计题目_Java课程设计
  9. android 旋转动画,android 动画rotate实现图片不停旋转的效果
  10. 知乎提示浏览器版本过低怎么办
  11. T8 ADS1299开发板的默认设置
  12. SVO2:一些失败的经验
  13. c语言——求逆矩阵,伴随矩阵,行列式
  14. 常见鸟的种类及特点_鸟的种类(常见鸟的名字大全)
  15. TCP序列号(Sequence Number)和确认号(Acknowledgment Number)
  16. 红米k30至尊纪念版和华为mate30pro哪个值得买
  17. docker 部署 gitlab gitlab-runner 实现 CI
  18. 仿vivo控制中心下载_手机控制中心app
  19. 【JAVA】网页版登录注册系统
  20. 自定义ro.build.fingerprint

热门文章

  1. 52. N-Queens II
  2. python做基本的图像处理
  3. Python3实现简单可学习的手写体识别
  4. ArcGIS 10.0 ArcGIS 9.3.1数据生成实验--个人地理数据库
  5. leveldb 学习。
  6. Windows Form -----内容(2)
  7. 为什么要用内部类:控制框架【转】
  8. 转,mysql的select * into
  9. 数据结构趣题——顺序表就地逆置
  10. python apache配置_Apache运行Python的配置