文本进度条实例
#!/usr/bin/env python3 import time #for i in range(101): # print (" {:3.0f}%".format(i),end="") # time.sleep(0.1) scale = 50 print("执行开始".center(scale//2,"-")) start = time.perf_counter() for i in range(scale+1): a = '*' * i b = '-' * (scale - i) c = (i/scale)*100 time.sleep(0.1) dur = time.perf_counter() - start print (" {:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,dur),end="") print("") print("执行结束".center(scale//2,"-"))
BMI指数计算(if条件)
#!/usr/bin/env python3 def BMI(): height,weight = eval(input("请输入身高(米)和体重(公斤)[逗号隔开]:")) bmi = weight / pow(height,2) print("BMI指数为:{:0.2f}".format(bmi)) who,nat="","" if bmi < 18.5: who, nat = "偏瘦","偏瘦" elif 18.5 <= bmi < 24: who, nat = "正常","正常" elif 24 <= bmi < 25: who, nat = "正常","偏胖" elif 25 <= bmi < 28: who, nat = "偏胖","偏胖" elif 28 <= bmi < 30: who, nat = "偏胖","肥胖" else: who, nat = "肥胖","肥胖" print("BMI指标为:国际:{} 国内:{}".format(who,nat)) try: BMI() except: print("输入错误")
π值计算(公式和蒙特卡罗方法)
#!/usr/bin/env python3 #计算pi pi = 0 N = 100 for k in range(N): pi += 1/pow(16,k)*(4/(8*k+1)-2/(8*k+4)-1/(8*k+5)-1/(8*k+6)) print("圆周率是:{}".format(pi)) #蒙特卡洛方法 from random import random from time import perf_counter DARTS = 1000*1000 hits = 0.0 start = perf_counter() for i in range(1,DARTS+1): x,y = random(),random() dist = pow(x**2+y**2,0.5) if dist <= 1.0: hits += 1 pi = 4* (hits/DARTS) print("圆周率是:{}".format(pi)) print("运行时间是:{:.2f}s".format(perf_counter()-start))
异常处理
#!/usr/bin/env python3 try: num = eval(input("请输入一个整数:")) print(num ** 2) except:#try执行错误后执行 print("输入错误") else:#正常运行后执行 print("输入正确") finally:#无论try是否执行正确,在最后都会执行 print("程序结束")
递归实例:斐波那契数列、汉诺塔、科赫雪花
#!/usr/bin/env python3 #斐波那契数列 def fibo(n): if n == 1 or n == 2: return 1 else: return fibo(n-1)+fibo(n-2) print(fibo(8)) #汉诺塔 def hano(n,src,mid,dst): if n == 1: print(n,"{}->{}".format(src,dst)) else: hano(n-1,src,dst,mid) print(n,"{}->{}".format(src,dst)) hano(n-1,mid,src,dst) hano(3,"A","B","C") #科赫雪花 import turtle def koch(size,n): if n == 0: turtle.fd(size) else: for angle in [0,60,-120,60]: turtle.left(angle) koch(size/3,n-1) def main(): turtle.setup(800,800) turtle.penup() turtle.goto(-200,100) turtle.pendown() turtle.pensize(2) level = 3 koch(400,level) turtle.right(120) koch(400,level) turtle.right(120) koch(400,level) turtle.hideturtle() main()
词频统计
#统计单词频率 def getTtext(filename): txt = open(filename,'r',encoding='utf-8').read() txt = txt.lower() for ch in '!"#$%&()*+,-./:;<=>?@[\]^_‘{|}~': txt = txt.replace(ch,' ') return txt text = getTtext('text.txt') words = text.split() counts = {} for word in words: counts[word] = counts.get(word,0) + 1 items = list(counts.items()) items.sort(key=lambda x:x[1],reverse=True) for i in range(10): word,count = items[i] print("{0:<10}{1:>5}".format(word,count))
jieba jieba分词的三种模式
# 精确模式:jieba.lcut把文本的切分开,不存在冗余单词
# 全模式:把文本中所有可能的词语都扫描出来,冗余
# 搜索引擎模式:在精确基础上,对长词再次切分
In [1]: import jieba In [2]: jieba.lcut("中国是一个伟大的国家"). Out[2]: ['中国', '是', '一个', '伟大', '的', '国家'] In [3]: jieba.lcut("中国是一个伟大的国家",cut_all=True) Out[3]: ['中国', '国是', '一个', '伟大', '的', '国家'] In [4]: jieba.lcut_for_search("中华人民共和国是伟大的") Out[4]: ['中华', '华人', '人民', '共和', '共和国', '中华人民共和国', '是', '伟大', '的'] In [5]: jieba.add_word("故园旧梦")