2020.10.19## 标题
数字游戏
from tkinter import *
from random import randint
import tkinter.simpledialog as dl
import tkinter.messagebox as mb
root = Tk()
w = Label(root, text = “Label Title”)
w.pack() #使文字与对话框相适应
mb.showinfo(“猜数字”, “欢迎来到猜数字游戏!”) #输出一个对话框
while True:
#接收一个整数,并返回
guess = dl.askinteger(“数字”, “please enter a numble between 1 and 10:”)
if guess == randint(1,10):
output = “yes”
break
else:
output = “no”
点名游戏
from tkinter import *
import time
class RandomName(Frame):
def init(self, parent=None, **kw):
Frame.init(self, parent, kw)
self.name_list = []
self._start = 0.0
self._elapsedtime = 0.0
self._running = False
self.timestr = StringVar()
self.makeWidgets()
def makeWidgets(self):
# 定义标签栏
l = Label(self, textvariable=self.timestr, font=("Arial, 35"))
self.set_name(self._elapsedtime)
l.pack(side=TOP)
def update(self):
# 更新显示内容
self._elapsedtime = time.time() - self._start
self.set_name(self._elapsedtime) # 设置显示内容
self._timer = self.after(50, self.update) # 刷新界面
def set_name(self, elap):
# 随机产生姓名
cur = int(elap * 100 % 30)
name_list = ['王生安', '李鑫灏', '薛佛世', '蔡壮保', '钱勤堃', '潘恩依', '陈国柏', '魏皑虎',
'周卓浩', '汤辟邦', '张顺谷', '张悌斯', '张灶冲', '易江维', '孙来笙', '饶展林',
'岳列洋', '时党舒', '周迟蒲', '廉梦容', '张淮森', '夏劲釜', '王好隐', '刘昼星',
'池荣弈', '邹包幼', '王施峪', '武慎萌', '范千皋', '潘佩焱']
self.timestr.set(name_list[cur])
def Start(self):
# 开始
if not self._running:
self._start = time.time() - self._elapsedtime
self.update()
self._running = True
def Stop(self):
# 暂停
if self._running:
self.after_cancel(self._timer)
self._elapsedtime = time.time() - self._start
self.set_name(self._elapsedtime)
self._running = False
def name_label(self):
# 显示窗口
self.pack(side=TOP)
Button(self, text='start', command=self.Start, width=10, height=2).pack(side=LEFT)
Button(self, text='stop', command=self.Stop, width=10, height=2).pack(side=LEFT)
if name == ‘main’:
root = Tk()
root.title(“Aloe”)
root.geometry(‘250x150’)
sw = RandomName(root)
sw.name_label()
root.mainloop()
统计单词频率
以walden的文本为例,代码如下:
import re
with open(‘walden.txt’) as file:
file_txt=file.read()
word_text=re.sub(r’[?.!,;""/[]]’,’ ',file_txt) #将?!等符号转化成空格
wordlist=word_texts.split()
word_dict={}
for word in wordlist:
if word not in word_dict:
word_dict[word]=1
else:
word_dict[word]=word_dict.get(word)+1
dict_order=dict(sorted(word_dict.items(),key=lambda x:x[1],reverse=True))#对单词进行排序,reverse的True和False决定着正序还是倒序
排序去重复
排序
a=[1,2,6,0.3,2,0.5,-1,2.4]
a.sort()
print(a)
去掉重复的元素
lst = eval(input(“请输入列表lst:”))
lst = set(lst)
print(lst)