代码:
# 创建一个程序,可指定密码长度,生成一串随机密码
# 创建一个数字+大小写字母+特殊字符的字符串。根据设定的密码长度随机生成一串密码
import random
passwd_len = int(input('请输入密码长度:'))
# 创建一个数字+大小写字母+特殊字符的字符串
str1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@#$%^&*"
# 将列表转换成字符串
password = "".join(random.sample(str1, passwd_len))
print(password)
执行效果:
代码:
"""
目标:通过用户提供的输入,生成随机且唯一的句子
提示:以用户输入的名词、代词、形容词等作为输入,然后将所有数据添加到句子,并将其组合返回
"""
color = input('Please enter a color:')
pluralNoun = input('Enter a plural noun:')
celebrity = input("Enter a celebrity:")
print(f'Rose are {color}, {pluralNoun} are blue. I like {celebrity}')
执行效果:
代码:
"""
目标:每次用户运行程序时,都会生成一个随机的故事
提示:random模块可以用来选择故事的随机部分,内容来自每个列表
"""
import random
when = ['A few years ago', 'Long long ago', 'Long ago', 'Recently', 'A few days ago', 'Last night', 'On 20th Jan']
who = ['a rabbit', 'a monkey', 'a tiger', 'a turtle', 'a cat', 'a farmer', 'a monk', 'a thief', 'a policeman', 'a rich man', 'a landlord']
name = ['Tom', 'Jack', 'Lucy', 'Buff', 'Coco', 'David', 'July']
residence = ['Japan', 'England', 'Germany', 'India', 'Cuba']
went = ['cinema', 'university', 'school', 'laundry']
happened = ['made a lot of friends', 'wrote a book', 'found a batch of treasures', 'found a magic lamp']
print(random.choice(when) + ', ' + random.choice(who) + ' that lived in ' +
random.choice(residence) + ', went to the ' + random.choice(went) + ' and ' +
random.choice(happened) + '.')
执行效果:
代码:
"""
目标:编写一个Python脚本,从邮件地址中获取用户名和域名
提示:使用@作为分隔符,将地址分成两个字符串
"""
# 获取用户输入的邮箱
email = input('请输入您的邮件地址:').strip()
# 获取用户名
user_name = email[:email.index('@')]
# 获取域名
domain_name = email[email.index('@'):]
print(f'用户名为:{user_name},域名为:{domain_name}')
执行效果:
代码:
"""
目标:编写python脚本,用于发送电子邮件
提示:email库可用于发送电子邮件
"""
import smtplib
from email.message import EmailMessage
# 创建一个邮件对象
email = EmailMessage()
# 发件人
email['from'] = '[email protected]'
# 收件人
email['to'] = '[email protected]'
# 主题
email['subject'] = 'This is a test'
# 内容
email.set_content('content of test')
# 发送请求
# host='smtp.gmail.com', port=587
with smtplib.SMTP(host='smtp.163.com', port=25) as smtp:
smtp.ehlo() # 服务器对象
smtp.starttls() # 服务器 与客户端之间发送数据
smtp.login("[email protected]", "123456") # 用户名及授权码登录
smtp.send_message(email) # 发送邮件
print("success")
执行效果:
代码:
"""
目标: 编写一个Python脚本,从给定的句子生成一个缩写词
提示:可以通过拆分和索引来获取第一个单词,然后将其组合
"""
# 获取用户输入的句子,并分割,成为一个列表
text = input("输入英文字符串:").split()
acronym = ""
for i in text:
# 将每个单词的首字母转换成大写,组合成一个字符串
acronym += i[0].upper()
print(acronym)
执行效果:
代码:
"""
编写Python脚本,通过为路径选择不同的选项让用户进行有趣的冒险
"""
name = input('Enter your name:')
print(f"Hello, {name}! You are stuck in a forest. Your task is to get out from the forest without dieing")
print("You're walking threw forest and suddenly a wolf comes in your way. Now you have two options.")
print("1.Run 2.Climb the nearest tree")
user = int(input('Choose one option 1 or 2:'))
if user == 1:
print('GG!')
elif user == 2:
print('Success!')
else:
print("Incorrect Input!")
执行效果:
代码:
"""
目标:编写一个创建闹钟的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]
print("Setting up alarm...")
while True:
# 获取当前时间
now = datetime.now()
# 小时,24小时制
current_hour = now.strftime('%H')
# 分钟
current_minute = now.strftime('%M')
# 秒
current_seconds = now.strftime('%S')
# am/pm
#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('起床号.mp3')
break
执行效果:
代码:
"""
目标:编写一个python脚本,可以检测图像中的人脸,并将所有的人脸保存在一个文件夹中
提示:可以使用haar级联分类器对人脸进行检测,返回的人脸坐标信息,可以保存在一个文件中
"""
import cv2
""""
Could not find a version that satisfies the requirement cv2 (from versions: )
解决办法:pip install opencv-python
"""
# 加载检测库
face_cascade = cv2.CascadeClassifier('D:\software\Python\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
# 读取图片
img = cv2.imread('huge.jpeg')
# 转换成灰度
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 人脸检测
faces = face_cascade.detectMultiScale(gray, 1.3, 4)
# 围绕人脸绘制矩形
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 )
# 输出展示
cv2.imshow('img', img)
cv2.imshow('imgcropped', crop_face)
cv2.waitKey()
测试图片::
执行效果:
生成的图片效果:
代码:
"""
目标:创建一个命令行游戏,玩家可以在石头、剪刀和布之间进行选择,与计算机PK
"""
import random
choices = ['石头', '剪刀', '布']
# 计算机从石头、剪刀、布中随机选取一个
computer = random.choice(choices)
player = False
# 初始分数均为0
player_score = computer_score = 0
while True:
player = input("石头、剪刀还是布?")
# 玩家和电脑出的一样----平局
if player == computer:
print(f"玩家:{player} 电脑:{computer}------平局!")
# 玩家获胜的情况:1--玩家出石头,电脑出剪刀;2--玩家出剪刀,电脑出布;3--玩家出布,电脑出石头
elif (player == '石头' and computer == '剪刀') or (player == '剪刀' and computer == '布') or (player == '布' and computer == '石头'):
print(f"玩家:{player} 电脑:{computer}------玩家胜!")
player_score += 1
# 电脑获胜的情况,与玩家获胜类似
elif (computer == '石头' and player == '剪刀') or (computer == '剪刀' and player == '布') or (computer == '布' and player == '石头'):
print(f"玩家:{player} 电脑:{computer}------电脑胜!")
computer_score += 1
else:
exit()
print(f"当前比分:玩家{player_score}:电脑{computer_score}")
执行效果:
代码:
"""
目标:创建一个脚本,在一个范围内生成一个随机整数
"""
import random
print("请设置数字范围:")
min_num = int(input("最小值:"))
max_num = int(input("最大值:"))
# 在设置的范围内随机生成一个整数
number = random.randint(min_num, max_num)
for i in range(0, 3):
guess = int(input("猜猜这个数是多少?"))
if guess == number:
print(f'猜对了!不愧是你!')
# 猜对了就退出循环
break
elif guess > number:
print(f"不对,这个数要比{guess}小!")
elif guess < number:
print(f"不对,这个数要比{guess}大!")
else:
print(f"很遗憾,正确答案是:{number}")
执行效果:
代码:
"""
目标:创建一个简单的命令行hangman游戏
提示:创建一个密码词的列表并随机选择一个单词。将每个单词用下划线”_“
表示,给用户提供猜单词的机会,如果用户猜对了单词,则将”_“用单词替换
"""
import random
import time
name = input("What's your name?")
print(f"Hello, {name}! Time to play hangman!")
time.sleep(1)
print("Start guessing...")
time.sleep(0.5)
# 单词列表
words = ['python', 'programming', 'treasure', 'creative', 'medium', 'honor', 'wonderful']
word = random.choice(words)
guesses = ''
turns = 5
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print(char, end="")
else:
print("_", end="")
failed += 1
if failed == 0:
print('You win!')
break
guess = input("\nguess a character:")
guesses += guess
if guess not in word:
turns -= 1
print("Wrong")
print(f"You have {turns} more guesses")
if turns == 0:
print(f"You lose!Answer is {word}")
执行效果:
代码:
"""
目标:编写一个Python脚本,用于将pdf文件转换成有声读物
提示:借助pyttsx3库将文本转换成语音
"""
import PyPDF2 as PyPDF2
import pyttsx3 as pyttsx3
pdfReader = PyPDF2.PdfFileReader(open('test.pdf', 'rb'))
speaker = pyttsx3.init()
for page_num in range(pdfReader.numPages):
# 获取pdf中的内容
text = pdfReader.getPage(page_num).extractText()
print(text)
speaker.say(text)
# 执行
speaker.runAndWait()
speaker.stop()
test.pdf::
代码:
# 目标:编写一个Python脚本,接收城市名称并使用爬虫获取该城市的天气信息
import pyttsx3
import requests
from lxml import etree
def get_weather(city):
# 天气的网站网址 字符串
url = 'https://www.tianqi.com/' + city + '/'
# 伪装浏览器的马甲
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36 Edg/83.0.478.58'
}
# 发起网络请求并获取网页代码
website = requests.get(url=url, headers=headers)
data = etree.HTML(website.text) # 数据预处理
# xpath解析页面天气数据
weather_list = data.xpath('//dl[@class="weather_info"]//text()')
print(weather_list)
weather_list = list(filter(lambda x: x.strip('[切换城市]').strip(), weather_list))
weather_list[2] = "".join(weather_list[2:4])
weather_list.remove(weather_list[3])
print(weather_list)
weather_text = '欢迎使用天气播报助手,以下是您想要了解的城市天气:\n'
for text in weather_list:
weather_text += text + "\t"
print(weather_text)
return weather_text
if __name__ == '__main__':
city = input('请输入城市的拼音(例如:广州-->guangzhou):').strip()
weather_info = get_weather(city) # weather_info来获取抓取到的天气文字
# 初始化说话的对象
weather = pyttsx3.init()
# 获取发音人
voices = weather.getProperty('voices')
# 设置发音人(注意中英文)
weather.setProperty('voice', voices[0].id)
# 改变语速 范围为0-200 默认值为200
rate = weather.getProperty('rate')
weather.setProperty('rate', rate - 50)
# 设置音量 范围为0.0-1.0 默认值为1.0
weather.setProperty('volume', 0.7)
# 预设要朗读的文本数据
weather.say(weather_info)
# 开始执行说话的操作
weather.runAndWait()
执行效果:
代码:
"""
目标:创建一个提醒应用程序,在特定的时间提醒你做一些事情
提示:Time模块可以用来跟踪提醒时间,toastnotifier库可以用来显示桌面通知
win10toast是一个windows通知的触发框架,使用它可以轻松的调起系统通知。通过它可以很方便的做一个定时通知的功能应用。
"""
import time
from win10toast import ToastNotifier
toaster = ToastNotifier()
try:
# 标题
header = input("Title of reminder:")
# 提醒消息
text = input("Message of reminder:")
# 多少分钟之后提醒
time_min = float(input("In how many minutes?"))
except:
header = input("Title of reminder:")
text = input("Message of reminder:")
time_min = float(input("In how many minutes?"))
time_min *= 60
print("Setting up reminder...")
time.sleep(2)
print("all set!")
time.sleep(time_min)
# duration:持续时间
toaster.show_toast(f'{header}', f"{text}", duration=10, threaded=True)
while toaster.notification_active(): time.sleep(0.005)
执行效果:
代码:
"""
目标:编写一个Python脚本,将用户按下的所有键保存在一个文本文件中
提示:pynput是Python中的一个库,用于控制键盘和鼠标的移动,它也可以用于制作键盘记录器
"""
from pynput.keyboard import Key, Controller, Listener
keyboard = Controller()
keys = []
def on_press(key):
global keys
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()
执行效果:
参考链接: