上机练习
给算法计时
阶乘累加(n=1~100)各需要多长时间
# 给算法计时,阶乘累加(n=1~100)各需要多长时间
import time
t1 = time.time()
t = 1
s = 0
for b in range(1, 101):
t = t * b
s = s + t
t2 = time.time()
print(t2-t1)
文件处理:文本文件写入
将一篇文章写入一个文本文件
f = open("my.txt", "w")
f.write("hello,world\n")
f.close()
f = open("my.txt","r")
f.readlines()
f.close()
文本处理:文本文件读取
读出文本文件,统计单词数输出
读出文本文件,随机输出其中10个单词
# 读出文本文件,统计单词数输出,随机输出其中10个单词
import random
f = open("my1","r")
# 去除文本中的换行符
content = f.read().replace('\n',' ')
#contents = ''
# 去除标点符号
for i in "!@#$%^&*()~:,.';{}[]|/?-<>...":
contents = content.replace(i,' ')
# 用列表a存储每一个单词
a = contents.split(' ')
# 去除所有空格元素,获得文本中单词总数
for j in a:
if '' in a:
a.remove('')
print(len(a))
print(random.sample(a,10))