2026寒假学习Pyhon_4_day

1
2
3
path = "d:\\"
f = open(path+"a.txt","rt")
print(f.readline())
全国计算机等级考试
1
2
f.close()
print(f.readline())
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-3-b3bdf0673a96> in <module>()
      1 f.close()
----> 2 print(f.readline())


ValueError: I/O operation on closed file.
1
2
3
f = open("D://b.txt","r")
s = f.read()
print(s)
新年都未有芳华,二月初惊见草芽。
白雪却嫌春色晚,故穿庭树作飞花。
1
f.close()
1
2
3
f = open("D://b.txt","r")
ls = f.readlines()
print(ls)
['新年都未有芳华,二月初惊见草芽。\n', '白雪却嫌春色晚,故穿庭树作飞花。']
1
f.close()
1
2
3
4
f = open("D:\\b.txt","r")
for line in f:
print(line)
f.close()
新年都未有芳华,二月初惊见草芽。

白雪却嫌春色晚,故穿庭树作飞花。
1
2
3
4
f = open("d:\\c.txt","w")
f.write("新年都未有芳华\n")
f.write("二月初惊见草芽\n")
f.close()
1
2
3
4
ls = ['北京','上海','天津','重庆']
f = open("d:\\city.csv","w")
f.write(",".join(ls)+"\n")
f.close()
1
2
3
4
f = open("d:\\city.csv","r")
ls = f.read().strip('\n').split(",")
f.close()
print(ls)
['北京', '上海', '天津', '重庆']
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ls = [ 
['指标', '2014年', '2015年', '2016年'],
['居民消费价格指数', '102', '101.4', '102'],
['食品', '103.1', '102.3', '104.6'],
['烟酒及用品', '994', '102.1', '101.5'],
['衣着', '102.4', '102.7', '101.4'],
['家庭设备用品', '101.2', '101', '100.5'],
['医疗保健和个人用品', '101.3', '102', '101.1'],
['交通和通信', '99.9', '98.3', '98.7'],
['娱乐教育文化', '101.9', '101.4', '101.6'],
['居住', '102', '100.7', '101.6'],
]
f = open("d:\\cpi.csv","w")
for row in ls:
f.write(",".join(row)+"\n")
f.close()
1
2
3
4
5
6
f = open("d:\\cpi.csv","r")
ls = []
for line in f:
ls.append(line.strip('\n').split(','))
f.close()
print(ls)
[['指标', '2014年', '2015年', '2016年'], ['居民消费价格指数', '102', '101.4', '102'], ['食品', '103.1', '102.3', '104.6'], ['烟酒及用品', '994', '102.1', '101.5'], ['衣着', '102.4', '102.7', '101.4'], ['家庭设备用品', '101.2', '101', '100.5'], ['医疗保健和个人用品', '101.3', '102', '101.1'], ['交通和通信', '99.9', '98.3', '98.7'], ['娱乐教育文化', '101.9', '101.4', '101.6'], ['居住', '102', '100.7', '101.6']]
1
2
3
4
5
for row in ls:
line = ""
for item in row:
line += "{:10}\t".format(item)
print(line)
指标        	2014年     	2015年     	2016年     	
居民消费价格指数  	102       	101.4     	102       	
食品        	103.1     	102.3     	104.6     	
烟酒及用品     	994       	102.1     	101.5     	
衣着        	102.4     	102.7     	101.4     	
家庭设备用品    	101.2     	101       	100.5     	
医疗保健和个人用品 	101.3     	102       	101.1     	
交通和通信     	99.9      	98.3      	98.7      	
娱乐教育文化    	101.9     	101.4     	101.6     	
居住        	102       	100.7     	101.6     	
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# FinancePredict.py
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 = [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 = []
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()
---------------------------------------------------------------------------

UnicodeDecodeError                        Traceback (most recent call last)

<ipython-input-39-f45289a2f30c> in <module>()
     50     showResults(newyears, dataNames, newDatas)
     51 
---> 52 main()


<ipython-input-39-f45289a2f30c> in main()
     44     newyears = [x+2010 for x in range(7)]
     45     newDatas = []
---> 46     years, dataNames, datas = parseCSV('finance.csv')
     47     for data in datas:
     48         a, b = linearRegression(years, data)


<ipython-input-39-f45289a2f30c> in parseCSV(filename)
      3     dataNames, data = [], []
      4     f = open(filename, 'r', encoding='utf-8')
----> 5     for line in f:
      6         splitedLine = line.strip().split(',')
      7         if '指标' in splitedLine[0]:


d:\Anaconda3\lib\codecs.py in decode(self, input, final)
    320         # decode input (taking the buffer into account)
    321         data = self.buffer + input
--> 322         (result, consumed) = self._buffer_decode(data, self.errors, final)
    323         # keep undecoded input until the next call
    324         self.buffer = data[consumed:]


UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb1 in position 2: invalid start byte
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def parseCSV(filename):
"""解析CSV文件,返回年份、数据名称和数据"""
dataNames, data = [], []
try:
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
splitedLine = line.strip().split(',')
if not splitedLine: # 跳过空行
continue

if '指标' in splitedLine[0]:
# 提取年份,处理可能的格式问题
years = []
for x in splitedLine[1:]:
try:
# 移除年份中的非数字字符(如"年"字)
year_str = ''.join(filter(str.isdigit, x))
if year_str:
years.append(int(year_str))
except (ValueError, IndexError):
continue
else:
dataNames.append(splitedLine[0].strip()) # 保留原始名称
# 转换数据,处理可能的空值或格式错误
row_data = []
for x in splitedLine[1:]:
try:
row_data.append(float(x.strip()))
except (ValueError, IndexError):
row_data.append(0.0) # 或根据需求处理
data.append(row_data)
except FileNotFoundError:
print(f"错误:找不到文件 {filename}")
return [], [], []
except Exception as e:
print(f"解析文件时出错: {e}")
return [], [], []

return years, dataNames, data

def means(data):
"""计算平均值"""
if not data:
return 0
return sum(data) / len(data)

def linearRegression(xlist, ylist):
"""线性回归计算,返回截距a和斜率b"""
if len(xlist) != len(ylist) or len(xlist) < 2:
raise ValueError("数据长度不一致或不足")

xmeans, ymeans = means(xlist), means(ylist)

# 计算斜率的分子和分母
bNumerator = 0.0
bDenominator = 0.0

for x, y in zip(xlist, ylist):
bNumerator += (x - xmeans) * (y - ymeans)
bDenominator += (x - xmeans) ** 2

# 避免除零错误
if abs(bDenominator) < 1e-10:
return ymeans, 0 # 垂直或无法计算

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)
print('-' * (10 + 10 * len(years))) # 分隔线

for name, lineData in zip(dataNames, newDatas):
line = f"{name:<10}" # 左对齐,宽度10
for data in lineData:
line += '{:>10.1f}'.format(data)
print(line)

def main():
"""主函数"""
newyears = [x + 2010 for x in range(7)]
newDatas = []

# 建议使用相对路径或配置文件
years, dataNames, datas = parseCSV('finance.csv') # 修改为相对路径

if not years or not dataNames or not datas:
print("数据加载失败,请检查文件路径和格式")
return

if len(datas[0]) != len(years):
print("数据维度不匹配")
return

for data in datas:
try:
a, b = linearRegression(years, data)
newDatas.append(calNewData(newyears, a, b))
except Exception as e:
print(f"计算回归时出错: {e}")
newDatas.append([0] * len(newyears))

showResults(newyears, dataNames, newDatas)

if __name__ == "__main__":
main()
解析文件时出错: 'utf-8' codec can't decode byte 0xb1 in position 2: invalid start byte
数据加载失败,请检查文件路径和格式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def main():
printIntro()
probA, probB, n = getInputs()
winsA, winsB = simNGames(n, probA, probB)
printSummary(winsA, winsB)

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 simNGames(n, probA, probB):
winsA, winsB = 0, 0
for i in range(n):
scoreA, scoreB = simOneGame(probA, probB)
if scoreA > scoreB:
winsA += 1
else:
winsB += 1
return winsA, winsB

def simOneGame(probA, probB):
scoreA, scoreB = 0, 0
serving = "A"
while not gameOver(scoreA, scoreB):
if serving == "A":
if random() < probA:
scoreA += 1
else:
serving="B"
else:
if random() < probB:
scoreB += 1
else:
serving="A"
return scoreA, scoreB

def gameOver(a,b):
return a==15 or b==15

def printSummary(winsA, winsB):
n = winsA + winsB
print("竞技分析开始,共模拟{}场比赛".format(n))
print("选手A获胜{}场比赛,占比{:0.1%}".format(winsA, winsA/n))
print("选手B获胜{}场比赛,占比{:0.1%}".format(winsB, winsB/n))
import random
main()
这个程序模拟两个选手A和B的某种竞技比赛
程序运行需要A和B的能力值(以0到1之间的小数表示)
请输入选手A的能力值(0-1): 0.45
请输入选手B的能力值(0-1): 0.5
模拟比赛的场次: 1000



---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-5-f1b1ae51ff1a> in <module>()
     51     print("选手B获胜{}场比赛,占比{:0.1%}".format(winsB, winsB/n))
     52 import random
---> 53 main()


<ipython-input-5-f1b1ae51ff1a> in main()
      3     printIntro()
      4     probA, probB, n = getInputs()
----> 5     winsA, winsB = simNGames(n, probA, probB)
      6     printSummary(winsA, winsB)
      7 


<ipython-input-5-f1b1ae51ff1a> in simNGames(n, probA, probB)
     19     winsA, winsB = 0, 0
     20     for i in range(n):
---> 21         scoreA, scoreB = simOneGame(probA, probB)
     22         if scoreA > scoreB:
     23             winsA += 1


<ipython-input-5-f1b1ae51ff1a> in simOneGame(probA, probB)
     31     while not gameOver(scoreA, scoreB):
     32         if serving == "A":
---> 33             if random() < probA:
     34                 scoreA += 1
     35             else:


TypeError: 'module' object is not callable
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# 这是经过DeepSeek修改后的代码
import random

def main():
printIntro()
probA, probB, n = getInputs()
winsA, winsB = simNGames(n, probA, probB)
printSummary(winsA, winsB)

def printIntro():
print("这个程序模拟两个选手A和B的某种竞技比赛")
print("程序运行需要A和B的能力值(以0到1之间的小数表示)")

def getInputs():
# 使用 float() 替代 eval() 更安全
a = float(input("请输入选手A的能力值(0-1): "))
b = float(input("请输入选手B的能力值(0-1): "))
n = int(input("模拟比赛的场次: "))
return a, b, n

def simNGames(n, probA, probB):
winsA, winsB = 0, 0
for i in range(n):
scoreA, scoreB = simOneGame(probA, probB)
if scoreA > scoreB:
winsA += 1
else:
winsB += 1 # 注意:这里包括了平局时B获胜的情况
return winsA, winsB

def simOneGame(probA, probB):
scoreA, scoreB = 0, 0
serving = "A"
while not gameOver(scoreA, scoreB):
if serving == "A":
if random.random() < probA: # 使用 random.random()
scoreA += 1
else:
serving = "B"
else:
if random.random() < probB:
scoreB += 1
else:
serving = "A"
return scoreA, scoreB

def gameOver(a, b):
return a == 15 or b == 15

def printSummary(winsA, winsB):
n = winsA + winsB
print("竞技分析开始,共模拟{}场比赛".format(n))
print("选手A获胜{}场比赛,占比{:0.1%}".format(winsA, winsA/n))
print("选手B获胜{}场比赛,占比{:0.1%}".format(winsB, winsB/n))

# 添加主程序入口
if __name__ == "__main__":
main()
这个程序模拟两个选手A和B的某种竞技比赛
程序运行需要A和B的能力值(以0到1之间的小数表示)
请输入选手A的能力值(0-1): 0.45
请输入选手B的能力值(0-1): 0.5
模拟比赛的场次: 1000
竞技分析开始,共模拟1000场比赛
选手A获胜357场比赛,占比35.7%
选手B获胜643场比赛,占比64.3%

基本的Python内置函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# 实例解析:Web页面元素提取
def main():
inputfile = 'nationalgeographic.html'
outputfile = 'nationalgeographic-urls.txt'
htmlLines = getHTMLlines(inputfile)
imageUrls = extractImageUrls(htmlLines)
showResults(imageUrls)
saveResults(outputfile, imageUrls)

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()

# 添加主程序入口
if __name__ == "__main__":
main()
---------------------------------------------------------------------------

FileNotFoundError                         Traceback (most recent call last)

<ipython-input-7-bee4dd86ccfe> in <module>()
     37 # 添加主程序入口
     38 if __name__ == "__main__":
---> 39     main()


<ipython-input-7-bee4dd86ccfe> in main()
      3     inputfile  = 'nationalgeographic.html'
      4     outputfile = 'nationalgeographic-urls.txt'
----> 5     htmlLines = getHTMLlines(inputfile)
      6     imageUrls = extractImageUrls(htmlLines)
      7     showResults(imageUrls)


<ipython-input-7-bee4dd86ccfe> in getHTMLlines(htmlpath)
      9 
     10 def getHTMLlines(htmlpath):
---> 11     f = open(htmlpath, "r", encoding='utf-8')
     12     ls = f.readlines()
     13     f.close()


FileNotFoundError: [Errno 2] No such file or directory: 'nationalgeographic.html'
1
2
3
# from turtle import *
# setup(1024, 768, 100, 200)
# circle(200)
1
2
from random import *
randint(10,30)
28
1
randint(10,30)
15
1
2
import time
time.localtime()
time.struct_time(tm_year=2026, tm_mon=2, tm_mday=5, tm_hour=13, tm_min=17, tm_sec=50, tm_wday=3, tm_yday=36, tm_isdst=0)
1
2
3
4
import time
t = time.localtime(now)
time.mktime(t)
time.ctime(time.mktime(t))
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-27-218e30bd2a23> in <module>()
      1 import time
----> 2 t = time.localtime(now)
      3 time.mktime(t)
      4 time.ctime(time.mktime(t))


NameError: name 'now' is not defined
1


2026寒假学习Pyhon_4_day
https://laowan-blog.pages.dev/2026/02/06/2026寒假学习Pyhon-4-day/
作者
老万
发布于
2026年2月6日
许可协议