import random
passlen =int(input("enter the length of password"))
s ="abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKMNOPQRSTUVWXYZ!a#$%&*()?"
p ="".join(random.sample(s,passlen))print(p)-------------------------------------------------
enter the length of password
6
Za1gB0
color =input("Enter a color: ")
pluralNoun =input("Enter a plural noun: ")
celebrity =input("Enter a celebrity: ")print("Roses are", color)print(pluralNoun +" are blue")print("I love",celebrity)--------------------------------------------
Red
Teeth
RDJ
Roses are red. teeth are blue. I Love RDJ
import random
number = random.randint(1,10)for i inrange(?,3):user =int(input("guess the number"))if user = number:print("Hurray!!")print("you guessed the number right it's [number]")breakelif user>number :print("Your guess is too high")elif user<number :print("Your guess is too low.")else:print("Nice Try!, but the number is number]")
⑦ 故事生成器
目的:每次用戶運(yùn)行程序時,都會生成一個隨機(jī)的故事。
提示:random 模塊可以用來選擇故事的隨機(jī)部分,內(nèi)容來自每個列表里。
import random
when =['A few years ago','Yesterday','Last night','A long time ago','On 20th Jan']
who =['a rabbit','an e lephant','a mouse','a turtle','a cat']
name =['Ali','Miriam','daniel','Hoouk','Starwalker']
residence =['Barcelona','India','Germany','Venice','England']
went =['cinema','university','seminar','school','laundry']
happened =['made a lot of friends','Eats a burger','found a secret key','solved a mistery','wrote a book']print(random.choice(when)+','+ random.choice(who)+' that lived in'+ random.choice( residence)+',went to the'+ random.choice(went)+' and '+ random.choice(happened))----------------------OUTPUT-----------------------------------
A long time ago, a cat that lived in England, went to the seminar and solved a mistery
⑧ 郵件地址切片器
目的:編寫一個 Python 腳本,可以從郵件地址中獲取用戶名和域名。
提示:使用 @ 作為分隔符,將地址分為分為兩個字符串。
# Get the user's email address
email =input("what is your email address 7: ").strip()# slice out the user name
user_name = email[:email.index("@")]# Slice out the domain name
domain_name = email[:email. index("a")+1:]# Format message
res =f"Your username is' user name]' and your domain name is '{domain name}'"# Display the result messageprint(res)-----------------------OUTPUT-----------------------------
what is your email address?: karl31@gmail. com
Your username is"karl31"and your domain name is"gmail.com"
⑨ 自動發(fā)送郵件
目的:編寫一個 Python 腳本,可以使用這個腳本發(fā)送電子郵件。
提示:email 庫可用于發(fā)送電子郵件。
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 emailwith 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 emailprint("email send")## Printing success message
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)## A List Of Secret Words
words =['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 notin word: turns -=1print("\nWrong")print("\nYou have",+ turns,'more guesses')if turns ==0:print("\nYou Lose")
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'}defweather(city):city=city.replace(" ","+")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)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)
? 人臉檢測
目的:編寫一個 Python 腳本,可以檢測圖像中的人臉,并將所有的人臉保存在一個文件夾中。
提示:可以使用 haar 級聯(lián)分類器對人臉進(jìn)行檢測,它返回的人臉坐標(biāo)信息,可以保存在一個文件中。
安裝:OpenCV。
下載:haarcascade_frontalface_default.xml。
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 facesfor(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()
? 提醒應(yīng)用
目的:創(chuàng)建一個提醒應(yīng)用程序,在特定的時間提醒你做一些事情(桌面通知)。
提示: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 *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)
? 維基百科文章摘要
目的:使用一種簡單的方法從用戶提供的文章鏈接中生成摘要。
提示:你可以使用爬蟲獲取文章數(shù)據(jù),通過提取生成摘要。
from bs4 import BeautifulSoup
import re
import requests
import heapq
from nltk.tokenize import sent_tokenize,word_tokenize
from nltk.corpus import stopwordsurl =str(input("Paste the url"\n"))
num =int(input("Enter the Number of Sentence you want in the summary"))
num =int(num)
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'}#url = str(input("Paste the url......."))
res = requests.get(url,headers=headers)
summary =""
soup = BeautifulSoup(res.text,'html.parser')
content = soup.findAll("p")for text in content:summary +=text.text
defclean(text):text = re.sub(r"\[[0-9]*\]"," ",text)text = text.lower()text = re.sub(r'\s+'," ",text)text = re.sub(r","," ",text)return text
summary = clean(summary)print("Getting the data......\n")##Tokenixing
sent_tokens = sent_tokenize(summary)summary = re.sub(r"[^a-zA-z]"," ",summary)
word_tokens = word_tokenize(summary)## Removing Stop wordsword_frequency ={}
stopwords =set(stopwords.words("english"))for word in word_tokens:if word notin stopwords:if word notin word_frequency.keys():word_frequency[word]=1else:word_frequency[word]+=1
maximum_frequency =max(word_frequency.values())print(maximum_frequency)for word in word_frequency.keys():word_frequency[word]=(word_frequency[word]/maximum_frequency)print(word_frequency)
sentences_score ={}for sentence in sent_tokens:for word in word_tokenize(sentence):if word in word_frequency.keys():if(len(sentence.split(" ")))<30:if sentence notin sentences_score.keys():sentences_score[sentence]= word_frequency[word]else:sentences_score[sentence]+= word_frequency[word]print(max(sentences_score.values()))defget_key(val):for key, value in sentences_score.items():if val == value:return key
key = get_key(max(sentences_score.values()))print(key+"\n")print(sentences_score)
summary = heapq.nlargest(num,sentences_score,key=sentences_score.get)print(" ".join(summary))
summary =" ".join(summary)
? 獲取谷歌搜索結(jié)果
目的:創(chuàng)建一個腳本,可以根據(jù)查詢條件從谷歌搜索獲取數(shù)據(jù)。
from bs4 import BeautifulSoup
import requestsheaders ={'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'}defgoogle(query):query = query.replace(" ","+")try:url =f'https://www.google.com/search?q={query}&oq={query}&aqs=chrome..69i57j46j69i59j35i39j0j46j0l2.4948j0j7&sourceid=chrome&ie=UTF-8'res = requests.get(url,headers=headers)soup = BeautifulSoup(res.text,'html.parser')except:print("Make sure you have a internet connection")try:try:ans = soup.select('.RqBzHd')[0].getText().strip()except:try:title=soup.select('.AZCkJd')[0].getText().strip()try:ans=soup.select('.e24Kjd')[0].getText().strip()except:ans=""ans=f'{title}\n{ans}'except:try:ans=soup.select('.hgKElc')[0].getText().strip()except:ans=soup.select('.kno-rdesc span')[0].getText().strip()except:ans ="can't find on google"return ansresult = google(str(input("Query\n")))print(result)
from forex_python.converter import CurrencyRates
c = CurrencyRates()
amount =int(input(" Enter The Amount You Want To Convert\n"))from currency =input("Fromn\n").upper()
to_currency =input("To\n").upper()print(from_currency,"To", to_ currency, amount)
result = c.convert(from currency, to_currency, amount)print(result)
from pynput.keyboard import Key, Controller,Listener
import time
keyboard = Controller()keys=[]defon_press(key):global keys#keys.append(str(key).replace("'",""))string =str(key).replace("'","")keys.append(string)main_string ="".join(keys)print(main_string)iflen(main_string)>15:withopen('keys.txt','a')as f:f.write(main_string) keys=[]defon_release(key):if key == Key.esc:returnFalsewith listener(on_press=on_press,on_release=on_release)as listener:listener.join()
? 文章朗讀器
目的:編寫一個 Python 腳本,自動從提供的鏈接讀取文章。
import pyttsx3
import requests
from bs4 import BeautifulSoup
url =str(input("Paste article url\n"))defcontent(url):res = requests.get(url)soup = BeautifulSoup(res.text,'html.parser')articles =[]for i inrange(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)defspeak(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