Python的各种第三方库,能够完成很多好玩的操作,给大家展现几个Python实现的小玩意,看看大家都做过没~
大家也可根据项目的目的及提示,自己构建解决方法,一起在评论区交流~
1、短网址生成器
编写一个Python脚本,使用API缩短给定的URL。
from __future__ import 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 = ('http://tinyurl.com/api-create.php?' +
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)
if __name__ == '__main__':
main()
A long time ago, a cat that lived in England, went to the seminar and solved a mistery
3、邮件地址切片器
编写一个Python脚本,可以从邮件地址中获取用户名和域名。
使用@作为分隔符,将地址分为分为两个字符串。
#Get the user 's email address
email = input("what is your email address ?: ").strip()
# Slice out the user name
email = input("what is your email address ?: ").strip()
# Slice out the user 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 message
print(res)
Red
Teeth
RDJ
Roses are red. teeth are blue. I Love RDJ
5、自动发送邮件
编写一个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
6、猜数字游戏
在这个游戏中,任务是创建一个脚本,能够在一个范围内生成一个随机数。如果用户在三次机会中猜对了数字,那么用户赢得游戏,否则用户输。
生成一个随机数,然后使用循环给用户三次猜测机会,根据用户的猜测打印最终的结果。
import random
nunber = random.randint(1,10)
for i in range(e,3):
user =int(input("guess the number"))
if user -number:
print("Hurray H")
print(f"you guessed the number right it's {number}")
break
elif user>number:
print("Your guess is too high")
elif userenuimber:
print(Your guess is too low.")
else:
print(f"Nice Try!,but the number is {number}")
7、石头剪刀布游戏
创建一个命令行游戏,游戏者可以在石头、剪刀和布之间进行选择,与计算机PK。如果游戏者赢了,得分就会添加,直到结束游戏时,最终的分数会展示给游戏者。
接收游戏者的选择,并且与计算机的选择进行比较。计算机的选择是从选择列表中随机选取的。如果游戏者获胜,则增加1分。
import random
choices = ["Rock", "Paper", "Scissors"]
computer = random.choice(choices)
player = False
cpu_score = 0
player_score = 0
while True:
player = input("Rock, Paper or Scissors?").capitalize()
# 判断游戏者和电脑的选择
if player == computer:
print("Tie!")
elif player == "Rock":
if computer == "Paper":
print("You lose!", computer, "covers", player)
cpu_score+=1
else:
print("You win!", player, "smashes", computer)
player_score+=1
elif player == "Paper":
if computer == "Scissors":
print("You lose!", computer, "cut", player)
cpu_score+=1
else:
print("You win!", player, "covers", computer)
player_score+=1
elif player == "Scissors":
if computer == "Rock":
print("You lose...", computer, "smashes", player)
cpu_score+=1
else:
print("You win!", player, "cut", computer)
player_score+=1
elif player=='E':
print("Final Scores:")
print(f"CPU:{cpu_score}")
print(f"Plaer:{player_score}")
break
else:
print("That's not a valid play. Check your spelling!")
computer = random.choice(choices)
8、维基百科文章摘要
使用一种简单的方法从用户提供的文章链接中生成摘要。
你可以使用爬虫获取文章数据,通过提取生成摘要。
from bs4 import BeautifulSoup
import re
import requests
import heapq
from nltk.tokenize import sent_tokenize,word_tokenize
from nltk.corpus import stopwords
url = 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
def clean(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 words
word_frequency = {}stopwords = set(stopwords.words("english"))
for word in word_tokens:
if word not in stopwords:
if word not in word_frequency.keys():
word_frequency[word]=1
else:
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(" "))) :
if sentence not in sentences_score.keys():
sentences_score[sentence] = word_frequency[word]
else:
sentences_score[sentence] += word_frequency[word]
print(max(sentences_score.values()))
def get_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)
9、随机密码生成器
创建一个程序,可指定密码长度,生成一串随机密码。
创建一个数字+大写字母+小写字母+特殊字符的字符串。根据设定的密码长度随机生成一串密码。
import random
passlen = int(input("enter the length of password"))
s="abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLNNOPQRSTUVWXYz!简#$x^6a()?p=.join(random.sample(s.passlen )
print(p)
Python Programming languagePPL
22、骰子模拟器
创建一个程序来模拟掷骰子
当用户询问时,使用random模块生成一个1到6之间的数字。
import random;
while int(input( ' Press 1 to roll the dice or 0 to exit:\n')): print(random.randint(1,6))
> Original: https://www.cnblogs.com/hahaa/p/15430438.html
> Author: 轻松学Python
> Title: 建议收藏!献给Python初学者的22个入门小项目,练手必备!
---
---
## **相关阅读**
## Title: python之sort与sorted函数的区别
# python之sort与sorted函数的区别
原创
[Rickyyan](https://blog.51cto.com/u_13691477)<time>2022-08-10 11:38:18</time>博主文章分类:[python](https://blog.51cto.com/u_13691477/category8) ©著作权
**_文章标签_ [sort()](https://blog.51cto.com/topic/sort.html) [sorted()](https://blog.51cto.com/topic/sorted.html) [排序](https://blog.51cto.com/topic/paixu.html) [python](https://blog.51cto.com/topic/python-2.html)** **_文章分类_ [Python](https://blog.51cto.com/nav/python) [编程语言](https://blog.51cto.com/nav/program)**
©著作权归作者所有:来自51CTO博客作者Rickyyan的原创作品,请联系作者获取转载授权,否则将追究法律责任
**sort与sorted方法主要区别:**
方法
应用对象
是否修改原对象
返回值
sort()
列表
是
None
sorted()
所有可迭代对象
否
返回新列表
**sort(self, key, reverse):**
reverse默认为False,升序
降序则,reverse=True
l = [9, 4, 2 ,5, 1, 2, 10]re = l.sort(reverse= True)print(l)print(re)#结果[10, 9, 5, 4, 2, 2, 1]None# 集合使用sort()print(set(l).sort())# 报错AttributeError: 'set' object has no attribute 'sort'
**sorted(__iterable, key, reverse)**
__iterable:可迭代对象,必须
key:排序字段,传入函数,可选
reverse:升序/降序,默认升序
l = [9, 4, 2 ,5, 1, 2, 10]s = set(l)print(s, '类型:',type(s))new_l = sorted(l)new_s = sorted(s)print('返回新列表:', new_l)print('返回新列表:', new_s)print('集合经过sorted()后,返回的是列表', type(new_s))print('原列表不变:', l)print('原集合不变:', s)# 执行结果{1, 2, 4, 5, 9, 10} 类型: 返回新列表: [1, 2, 2, 4, 5, 9, 10]返回新列表: [1, 2, 4, 5, 9, 10]集合经过sorted()后,返回的是列表 原列表不变: [9, 4, 2, 5, 1, 2, 10]原集合不变: {1, 2, 4, 5, 9, 10}
**指定key排序**
d = dict(z=3, a=9, f=6, e=1)# 以value字段排序,返回key列表new_d1 = sorted(d.keys(), key= lambda x:d[x])print(new_d1)# 以key排序,降序,返回key_value列表new_d2 = sorted(d.items(), key= lambda x:x[0], reverse= True)print(new_d2)# 执行结果['e', 'z', 'f', 'a'][('z', 3), ('f', 6), ('e', 1), ('a', 9)]
```
- 打赏
- 赞
- 收藏
- 评论
- *举报
下一篇:Linux之find命令详解
Original: https://blog.51cto.com/u_13691477/5563129
Author: Rickyyan
Title: python之sort与sorted函数的区别