二级备赛系列博文
ch7、文件
文件类型分类
- 文本文件,单一特定编码,例如UTF-8编码
- 二进制文件,按照非字符但特定格式形成的文件,例如
png
图片文件和avi
视频文件 - 二进制文件和文本文件的最主要区别是否有统一的字符编码。
文件打开方式
t
表示文本文件方式打开,文件经过编码形式字符串,打印出有含义的字符b
表示二进制文件方式打开,文件被解析为字节流
文件的读操作
read
和readlines
都是一次性读入文件的函数f.read()
是最常用的一次性读入文件的函数,其结果是一个字符串f.readlines()
也是一次性读入文件的函数,其结果是一个列表,每个元素是文件的一行。- 对文件的读写有一个读取指针,当从文件中读入内容后,读取指针将向前进,再次读取的内容将从指针的新位置开始。若想再从头开始需要用
f.seek
函数重置指针位置 - 文本文件可以看成是由行组成的组合类型,因此,可以使用遍历循环逐行遍历文件。
文件的写操作
f.write
向文件写入一个字符串,f.write(s)时,要显式的使用’\n’对写入文本进分行,如果不进行分行,每次写入的字符串会被连接起来f.writelines
将一个元素为字符串的列表写入文件,直接将列表类型的各元素连
接起来写入文件f
数据组织的维度
- 一维数据采用线性方式组织,采用列表形式表示
- 存储采用CSV格式(逗号分隔,形成一行)
- 二维数据采用二维表格方式组织
- 高位数据采用对象方式组织
字符串常用方法
str.join(iter)
是将iter变量的每一个元素后增加一个str字符串。str.split(sep)
能够根据sep
分隔字符串str
,分割后的内容以列表类型返回。
def parseCSV(filename):
dataNames, data = [], []
f = open(filename, "r", encoding = 'utf-8')
for line in f:
splitedLine = line.strip().split(',')
if '指标' in splitedLine[0]:
years = list(int(x[:-1]) for x in splitedLine[1:])
else:
dataNames.append("{:10}".format(splitedLine[0]))
data.append([float(x) for x in splitedLine[1:]])#最外层少加一个[]
f.close()
return years, dataNames, data
def means(data):
return sum(data) / len(data)
def linearRegression(xlist, ylist):
xmeans, ymeans = means(xlist), means(ylist)
bNumerator = - len(xlist) * xmeans * ymeans
bDenominator = -len(xlist) * xmeans ** 2
for x, y in zip(xlist, ylist):
bNumerator += x * y
bDenominator += x ** 2
b = bNumerator / bDenominator
a = ymeans - b * xmeans
return a, b
def calNewData(newyears, a, b):
return [(a+b*x) for x in newyears]
def showResults(years, dataNames, newDatas):
print("{:^60}".format("国家财政收支线性估计"))
header = '指标 '
for year in years:
header += "{:10}".format(year)
print(header)
for name, lineData in zip(dataNames, newDatas):
line = name #这里为什么要重新再赋值呢?
for data in lineData:
line += "{:>10.1f}".format(data)
print(line)
def main():
newyears = [x+2010 for x in range(7)]
newDatas = [] #错写成了newdatas
years, dataNames, datas = parseCSV("finance.csv")
for data in datas:
a, b = linearRegression(years, data)
newDatas.append(calNewData(newyears, a, b))
showResults(newyears, dataNames, newDatas)
main()
ch8 程序设计
from random import *
def printIntro():
print("这个程序模拟两个选手A和B的某种竞技比赛")
print("程序运行需要A和B的能力值(以0~1之间的小数表示)")
def getInputs():
a = eval(input("请输入选手A的能力值(0~1): "))
b = eval(input("请输入选手B的能力值(0~1): "))
n = eval(input("模拟比赛的场次: "))
return a, b, n
def gameOver(a, b):
return a==15 or b==15
def simOneGame(proA, proB):
scoreA, scoreB = 0, 0
serving = "A"
while not gameOver(scoreA, scoreB):
if serving == "A":
if(random() < proA):
scoreA += 1
else:
serving = "B"
else:
if(random() < proB):
scoreB += 1
else:
serving = "A"
return scoreA, scoreB
def simNGames(n, proA, proB):
winsA, winsB = 0, 0
for i in range(n):
scoreA, scoreB = simOneGame(proA, proB)
if (scoreA > scoreB):#冒号别忘了
winsA += 1
else:
winsB += 1
return winsA, winsB
def printSummary(winsA, winsB):
n = winsA + winsB
print("竞技分析开始,共模拟{}场比赛".format(n))
print("选手A获胜{}场比赛,占比{:.1%}".format(winsA, winsA/n))
print("选手B获胜{}场比赛,占比{:.1%}".format(winsB, winsB/n))
def main():
printIntro()
proA, proB, n = getInputs()
winsA, winsB = simNGames(n, proA, proB)
printSummary(winsA, winsB)
main()
提取WEB上的链接
def getHTMLlines(htmlpath):
f = open(htmlpath, "r", encoding='utf-8')
ls = f.readlines()
f.close()
return ls
def extractImageUrls(htmllist):
urls = []
for line in htmllist:
if 'img' in line:
url = line.split('src=')[-1].split('"')[1]
if 'http' in url:
urls.append(url)
return urls
def showResults(urls):
count = 0
for url in urls:
print('第{:2}和URL:{}'.format(count, url))
count += 1
def saveResults(filepath, urls):
f = open(filepath, "w")
for url in urls:
f.write(url+"\n")
f.close()
def main():
inputfile = 'nationalgeographic.html'
outputfile = 'nationalgeographic-urls.txt'
htmlLines = getHTMLlines(inputfile)
imageUrls = extractImageUrls(htmlLines)
showResults(imageUrls)
saveResults(outputfile, imageUrls)
main()