当前位置:   article > 正文

用python做一个小项目,怎么用python做项目_python写项目教程

python写项目教程

大家好,小编来为大家解答以下问题,用python做一个小项目,怎么用python做项目,今天让我们一起来看看吧!

在使用Python的过程中,我最喜欢的就是Python的各种第三方库,能够完成很多操作。

下面就给大家介绍22个通过Python构建的项目,以此来学习Python编程python简单代码游戏

大家也可根据项目的目的及提示,自己构建解决方法,提高编程水平。

① 骰子模拟器
目的:创建一个程序来模拟掷骰子。
提示:当用户询问时,使用random模块生成一个1到6之间的数字。
在这里插入图片描述
② 石头剪刀布游戏
目标:创建一个命令行游戏,游戏者可以在石头、剪刀和布之间进行选择,与计算机PK。如果游戏者赢了,得分就会添加,直到结束游戏时,最终的分数会展示给游戏者。

提示:接收游戏者的选择,并且与计算机的选择进行比较。计算机的选择是从选择列表中随机选取的。如果游戏者获胜,则增加1分。

  1. import random
  2. choices = ["Rock", "Paper", "Scissors"]
  3. computer = random.choice(choices)
  4. player = False
  5. cpu_score = 0
  6. player_score = 0
  7. while True:
  8. player = input("Rock, Paper or Scissors?").capitalize()
  9. # 判断游戏者和电脑的选择
  10. if player == computer:
  11. print("Tie!")
  12. elif player == "Rock":
  13. if computer == "Paper":
  14. print("You lose!", computer, "covers", player)
  15. cpu_score+=1
  16. else:
  17. print("You win!", player, "smashes", computer)
  18. player_score+=1
  19. elif player == "Paper":
  20. if computer == "Scissors":
  21. print("You lose!", computer, "cut", player)
  22. cpu_score+=1
  23. else:
  24. print("You win!", player, "covers", computer)
  25. player_score+=1
  26. elif player == "Scissors":
  27. if computer == "Rock":
  28. print("You lose...", computer, "smashes", player)
  29. cpu_score+=1
  30. else:
  31. print("You win!", player, "cut", computer)
  32. player_score+=1
  33. elif player=='E':
  34. print("Final Scores:")
  35. print(f"CPU:{cpu_score}")
  36. print(f"Plaer:{player_score}")
  37. break
  38. else:
  39. print("That's not a valid play. Check your spelling!")
  40. computer = random.choice(choices)

③ 随机密码生成器
目标:创建一个程序,可指定密码长度,生成一串随机密码。

提示:创建一个数字+大写字母+小写字母+特殊字符的字符串。根据设定的密码长度随机生成一串密码。
在这里插入图片描述
④ 句子生成器
在这里插入图片描述
目的:通过用户提供的输入,来生成随机且唯一的句子。

提示:以用户输入的名词、代词、形容词等作为输入,然后将所有数据添加到句子中,并将其组合返回。

⑤ 猜数字游戏
目的:在这个游戏中,任务是创建一个脚本,能够在一个范围内生成一个随机数。如果用户在三次机会中猜对了数字,那么用户赢得游戏,否则用户输。

提示:生成一个随机数,然后使用循环给用户三次猜测机会,根据用户的猜测打印最终的结果。
在这里插入图片描述
⑥ 故事生成器
目的:每次用户运行程序时,都会生成一个随机的故事。

提示:random模块可以用来选择故事的随机部分,内容来自每个列表里。
在这里插入图片描述
⑦ 邮件地址切片器
目的:编写一个Python脚本,可以从邮件地址中获取用户名和域名。

提示:使用@作为分隔符,将地址分为分为两个字符串。
在这里插入图片描述
⑧ 自动发送邮件
目的:编写一个Python脚本,可以使用这个脚本发送电子邮件。

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

  1. import smtplib
  2. from email.message import EmailMessage
  3. email = EmailMessage() ## Creating a object for EmailMessage
  4. email['from'] = 'xyz name' ## Person who is sending
  5. email['to'] = 'xyz id' ## Whom we are sending
  6. email['subject'] = 'xyz subject' ## Subject of email
  7. email.set_content("Xyz content of email") ## content of email
  8. with smtlib.SMTP(host='smtp.gmail.com',port=587)as smtp:
  9. ## sending request to server
  10. smtp.ehlo() ## server object
  11. smtp.starttls() ## used to send data between server and client
  12. smtp.login("email_id","Password") ## login id and password of gmail
  13. smtp.send_message(email) ## Sending email
  14. print("email send") ## Printing success message

⑨ 缩写词
目的:编写一个Python脚本,从给定的句子生成一个缩写词。

提示:你可以通过拆分和索引来获取第一个单词,然后将其组合。
在这里插入图片描述
⑩ 文字冒险游戏
目的:编写一个有趣的Python脚本,通过为路径选择不同的选项让用户进行有趣的冒险。
在这里插入图片描述
在学习python中有任何困难不懂的可以微信扫描下方CSDN官方认证二维码

⑪ Hangman
目的:创建一个简单的命令行hangman游戏。

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

  1. 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)
  2. ## A List Of Secret Words words = ['python','programming','treasure','creative','medium','horror'] word
  3. = random.choice(words) guesses = '' turns = 5 while turns > 0:
  4. failed = 0
  5. for char in word:
  6. if char in guesses:
  7. print (char,end="")
  8. else:
  9. print ("_",end=""),
  10. failed += 1
  11. if failed == 0:
  12. print ("\nYou won")
  13. break
  14. guess = input("\nguess a character:")
  15. guesses += guess
  16. if guess not in word:
  17. turns -= 1
  18. print("\nWrong")
  19. print("\nYou have", + turns, 'more guesses')
  20. if turns == 0:
  21. print ("\nYou Lose")

⑫ 闹钟
目的:编写一个创建闹钟的Python脚本。

提示:你可以使用date-time模块创建闹钟,以及playsound库播放声音。

  1. from datetime import datetime
  2. from playsound import playsound
  3. alarm_time = input("Enter the time of alarm to be set:HH:MM:SS\n")
  4. alarm_hour=alarm_time[0:2]
  5. alarm_minute=alarm_time[3:5]
  6. alarm_seconds=alarm_time[6:8]
  7. alarm_period = alarm_time[9:11].upper()
  8. print("Setting up alarm..")
  9. while True:
  10. now = datetime.now()
  11. current_hour = now.strftime("%I")
  12. current_minute = now.strftime("%M")
  13. current_seconds = now.strftime("%S")
  14. current_period = now.strftime("%p")
  15. if(alarm_period==current_period):
  16. if(alarm_hour==current_hour):
  17. if(alarm_minute==current_minute):
  18. if(alarm_seconds==current_seconds):
  19. print("Wake Up!")
  20. playsound('audio.mp3') ## download the alarm sound from link
  21. break

⑬ 有声读物
目的:编写一个Python脚本,用于将Pdf文件转换为有声读物。

提示:借助pyttsx3库将文本转换为语音。

安装:pyttsx3,PyPDF2
在这里插入图片描述
⑭ 天气应用
目的:编写一个Python脚本,接收城市名称并使用爬虫获取该城市的天气信息。

提示:你可以使用Beautifulsoup和requests库直接从谷歌主页爬取数据。

安装:requests,BeautifulSoup

  1. from bs4 import BeautifulSoup
  2. import requests
  3. 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'}
  4. def weather(city):
  5. city=city.replace(" ","+")
  6. 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)
  7. print("Searching in google......\n")
  8. soup = BeautifulSoup(res.text,'html.parser')
  9. location = soup.select('#wob_loc')[0].getText().strip()
  10. time = soup.select('#wob_dts')[0].getText().strip()
  11. info = soup.select('#wob_dc')[0].getText().strip()
  12. weather = soup.select('#wob_tm')[0].getText().strip()
  13. print(location)
  14. print(time)
  15. print(info)
  16. print(weather+"°C")
  17. print("enter the city name")
  18. city=input()
  19. city=city+" weather"
  20. weather(city)

⑮ 人脸检测
目的:编写一个Python脚本,可以检测图像中的人脸,并将所有的人脸保存在一个文件夹中。

提示:可以使用haar级联分类器对人脸进行检测。它返回的人脸坐标信息,可以保存在一个文件中。

安装:OpenCV。

下载:haarcascade_frontalface_default.xml

  1. import cv2
  2. # Load the cascade
  3. face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
  4. # Read the input image
  5. img = cv2.imread('images/img0.jpg')
  6. # Convert into grayscale
  7. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  8. # Detect faces
  9. faces = face_cascade.detectMultiScale(gray, 1.3, 4)
  10. # Draw rectangle around the faces
  11. for (x, y, w, h) in faces:
  12. cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
  13. crop_face = img[y:y + h, x:x + w]
  14. cv2.imwrite(str(w) + str(h) + '_faces.jpg', crop_face)
  15. # Display the output
  16. cv2.imshow('img', img)
  17. cv2.imshow("imgcropped",crop_face)
  18. cv2.waitKey()

⑯ 提醒应用
目的:创建一个提醒应用程序,在特定的时间提醒你做一些事情(桌面通知)。

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

安装:win10toast

  1. from win10toast import ToastNotifier
  2. import time
  3. toaster = ToastNotifier()
  4. try:
  5. print("Title of reminder")
  6. header = input()
  7. print("Message of reminder")
  8. text = input()
  9. print("In how many minutes?")
  10. time_min = input()
  11. time_min=float(time_min)
  12. except:
  13. header = input("Title of reminder\n")
  14. text = input("Message of remindar\n")
  15. time_min=float(input("In how many minutes?\n"))
  16. time_min = time_min * 60
  17. print("Setting up reminder..")
  18. time.sleep(2)
  19. print("all set!")
  20. time.sleep(time_min)
  21. toaster.show_toast(f"{header}",
  22. f"{text}",
  23. duration=10,
  24. threaded=True)
  25. while toaster.notification_active(): time.sleep(0.005)

⑰ 维基百科文章摘要
目的:使用一种简单的方法从用户提供的文章链接中生成摘要。

提示:你可以使用爬虫获取文章数据,通过提取生成摘要。

  1. from bs4 import BeautifulSoup
  2. import re
  3. import requests
  4. import heapq
  5. from nltk.tokenize import sent_tokenize,word_tokenize
  6. from nltk.corpus import stopwords
  7. url = str(input("Paste the url"\n"))
  8. num = int(input("Enter the Number of Sentence you want in the summary"))
  9. num = int(num)
  10. 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'}
  11. #url = str(input("Paste the url......."))
  12. res = requests.get(url,headers=headers)
  13. summary = ""
  14. soup = BeautifulSoup(res.text,'html.parser')
  15. content = soup.findAll("p")
  16. for text in content:
  17. summary +=text.text
  18. def clean(text):
  19. text = re.sub(r"\[[0-9]*\]"," ",text)
  20. text = text.lower()
  21. text = re.sub(r'\s+'," ",text)
  22. text = re.sub(r","," ",text)
  23. return text
  24. summary = clean(summary)
  25. print("Getting the data......\n")
  26. ##Tokenixing
  27. sent_tokens = sent_tokenize(summary)
  28. summary = re.sub(r"[^a-zA-z]"," ",summary)
  29. word_tokens = word_tokenize(summary)
  30. ## Removing Stop words
  31. word_frequency = {}
  32. stopwords = set(stopwords.words("english"))
  33. for word in word_tokens:
  34. if word not in stopwords:
  35. if word not in word_frequency.keys():
  36. word_frequency[word]=1
  37. else:
  38. word_frequency[word] +=1
  39. maximum_frequency = max(word_frequency.values())
  40. print(maximum_frequency)
  41. for word in word_frequency.keys():
  42. word_frequency[word] = (word_frequency[word]/maximum_frequency)
  43. print(word_frequency)
  44. sentences_score = {}
  45. for sentence in sent_tokens:
  46. for word in word_tokenize(sentence):
  47. if word in word_frequency.keys():
  48. if (len(sentence.split(" "))) <30:
  49. if sentence not in sentences_score.keys():
  50. sentences_score[sentence] = word_frequency[word]
  51. else:
  52. sentences_score[sentence] += word_frequency[word]
  53. print(max(sentences_score.values()))
  54. def get_key(val):
  55. for key, value in sentences_score.items():
  56. if val == value:
  57. return key
  58. key = get_key(max(sentences_score.values()))
  59. print(key+"\n")
  60. print(sentences_score)
  61. summary = heapq.nlargest(num,sentences_score,key=sentences_score.get)
  62. print(" ".join(summary))
  63. summary = " ".join(summary)

⑱ 获取谷歌搜索结果
目的:创建一个脚本,可以根据查询条件从谷歌搜索获取数据。

  1. from bs4 import BeautifulSoup
  2. import requests
  3. 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'}
  4. def google(query):
  5. query = query.replace(" ","+")
  6. try:
  7. url = f'https://www.google.com/search?q={query}&oq={query}&aqs=chrome..69i57j46j69i59j35i39j0j46j0l2.4948j0j7&sourceid=chrome&ie=UTF-8'
  8. res = requests.get(url,headers=headers)
  9. soup = BeautifulSoup(res.text,'html.parser')
  10. except:
  11. print("Make sure you have a internet connection")
  12. try:
  13. try:
  14. ans = soup.select('.RqBzHd')[0].getText().strip()
  15. except:
  16. try:
  17. title=soup.select('.AZCkJd')[0].getText().strip()
  18. try:
  19. ans=soup.select('.e24Kjd')[0].getText().strip()
  20. except:
  21. ans=""
  22. ans=f'{title}\n{ans}'
  23. except:
  24. try:
  25. ans=soup.select('.hgKElc')[0].getText().strip()
  26. except:
  27. ans=soup.select('.kno-rdesc span')[0].getText().strip()
  28. except:
  29. ans = "can't find on google"
  30. return ans
  31. result = google(str(input("Query\n")))
  32. print(result)

获取结果如下。
在这里插入图片描述
⑲ 货币换算器
目的:编写一个Python脚本,可以将一种货币转换为其他用户选择的货币。

提示:使用Python中的API,或者通过forex-python模块来获取实时的货币汇率。

安装:forex-python

⑳ 键盘记录器
目的:编写一个Python脚本,将用户按下的所有键保存在一个文本文件中。

提示:pynput是Python中的一个库,用于控制键盘和鼠标的移动,它也可以用于制作键盘记录器。简单地读取用户按下的键,并在一定数量的键后将它们保存在一个文本文件中。

  1. from pynput.keyboard import Key, Controller,Listener
  2. import time
  3. keyboard = Controller()
  4. keys=[]
  5. def on_press(key):
  6. global keys
  7. #keys.append(str(key).replace("'",""))
  8. string = str(key).replace("'","")
  9. keys.append(string)
  10. main_string = "".join(keys)
  11. print(main_string)
  12. if len(main_string)>15:
  13. with open('keys.txt', 'a') as f:
  14. f.write(main_string)
  15. keys= []
  16. def on_release(key):
  17. if key == Key.esc:
  18. return False
  19. with listener(on_press=on_press,on_release=on_release) as listener:
  20. listener.join()

㉑ 文章朗读器

目的:编写一个Python脚本,自动从提供的链接读取文章。

  1. import pyttsx3
  2. import requests
  3. from bs4 import BeautifulSoup
  4. url = str(input("Paste article url\n"))
  5. def content(url):
  6. res = requests.get(url)
  7. soup = BeautifulSoup(res.text,'html.parser')
  8. articles = []
  9. for i in range(len(soup.select('.p'))):
  10. article = soup.select('.p')[i].getText().strip()
  11. articles.append(article)
  12. contents = " ".join(articles)
  13. return contents
  14. engine = pyttsx3.init('sapi5')
  15. voices = engine.getProperty('voices')
  16. engine.setProperty('voice', voices[0].id)
  17. def speak(audio):
  18. engine.say(audio)
  19. engine.runAndWait()
  20. contents = content(url)
  21. ## print(contents) ## In case you want to see the content
  22. #engine.save_to_file
  23. #engine.runAndWait() ## In case if you want to save the article as a audio file

㉒ 短网址生成器

目的:编写一个Python脚本,使用API缩短给定的URL。

  1. from __future__ import with_statement
  2. import contextlib
  3. try:
  4. from urllib.parse import urlencode
  5. except ImportError:
  6. from urllib import urlencode
  7. try:
  8. from urllib.request import urlopen
  9. except ImportError:
  10. from urllib2 import urlopen
  11. import sys
  12. def make_tiny(url):
  13. request_url = ('http://tinyurl.com/api-create.php?' +
  14. urlencode({'url':url}))
  15. with contextlib.closing(urlopen(request_url)) as response:
  16. return response.read().decode('utf-8')
  17. def main():
  18. for tinyurl in map(make_tiny, sys.argv[1:]):
  19. print(tinyurl)
  20. if __name__ == '__main__':
  21. main()
  22. -----------------------------OUTPUT------------------------
  23. python url_shortener.py https://www.wikipedia.org/
  24. https://tinyurl.com/buf3qt3

以上就是今天分享的内容,针对上面这些项目,有的可以适当调整。

比如自动发送邮件,可以选择使用自己的QQ邮箱。

天气信息也可使用国内一些免费的API,维基百科可以对应百度百科,谷歌搜索可以对应百度搜索等等。

这些都是大伙可以思考的~

在学习python中有任何困难不懂的可以微信扫描下方CSDN官方认证二维码加入python交流学习
多多交流问题,互帮互助,这里有不错的学习教程和开发工具。

一、Python所有方向的学习路线

Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。
在这里插入图片描述

二、Python必备开发工具

在这里插入图片描述

三、Python视频合集

观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。
在这里插入图片描述

四、实战案例

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。在这里插入图片描述

五、Python练习题

检查学习结果。
在这里插入图片描述

六、面试资料

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。
在这里插入图片描述
在这里插入图片描述
最后,千万别辜负自己当时开始的一腔热血,一起变强大变优秀。

文章知识点与官方知识档案匹配,可进一步学习相关知识
Java技能树首页概览149912 人正在系统学习中
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/1003523
推荐阅读
相关标签
  

闽ICP备14008679号