高中信息技术(Python) 必修1 数据与计算 源代码

您所在的位置:网站首页 高一电脑课编程 高中信息技术(Python) 必修1 数据与计算 源代码

高中信息技术(Python) 必修1 数据与计算 源代码

2023-03-25 22:44| 来源: 网络整理| 查看: 265

本文章原文地址:https://www.cnblogs.com/BobHuang/p/15621121.html,原文体验更佳 教材P68中IDLE显示Python版本为3.7.0,所以建议使用Python3.7系列。

第一章 数据与信息 1.1 感知数据 1.2 数据、信息与知识 1.3 数据采集与编码 1.4 数据管理与安全 1.5 数据与大数据 第二章 算法与问题解决 2.1 算法概念及描述

P46 停车场车位探测

flag = int(input("输入车位状态值:")) if flag == 1: print("绿色") print("空车位") else: print("红色") print("非空车位") 2.2 算法的控制结构 2.3 用算法解决问题的过程 第三章 算法的程序实现 3.1 用计算机编程解决问题的一般过程

P67 绘制正n边形

import turtle n=int(input("请输入正多边形的边数n:")) a= int(input("请输入边长a:")) d=(n-2)*180/n t=turtle.Pen() for i in range(n): #重复执行n遍 t.forward (a) #向前绘制长度为a的线段 t.left(180-d) #向左旋转(180-d)度 3.2 Python语言程序设计

P68 计算4+13

>>> print(4+13) 17

P69 输出"Hello Python!"

>>> print("Hello"+" Python!") Hello Python!

教材'Hello Python!'错了。打印时并不输出类型的'',运行"Hello"+" Python!"是有单引号的。 P69 两个数求和

a=int(input("请输入正整数a:")) b=int(input("请输入正整数b:")) c=a+b print(c)

P71 in成员运算符示例

>>> "w" in "rw" True >>> "x" in "rw" False

P72 定义变量

>>> degress_cel=26.0 >>> degress_cel 26.0 >>> degress_cel="26.0" >>> degress_cel '26.0'

P72 赋值语句

>>> number=0 >>> number=number+1 >>> print(number) 1

P72 定义列表

>>> info=["BH60018","苹果",50]

P73 使用索引访问元素

>>> info=["BH60018","苹果",50] >>> info[2] 50 >>> s="Hello" >>> s[1] 'e'

P73 切片

>>> info[0:2] ['BH60018', '苹果'] >>> s[1:4] 'ell'

P74 字典

>>> dic={"铅笔":71,"钢笔":59,"橡皮":98,"尺子":92} >>> print(dic["铅笔"]) 71

P74 交换a和b

a=int(input("请输入整数a的值:")) b=int(input("请输入整数b的值:")) c=a #语句1 a=b #语句2 b=c #语句3 print("a=",a) print("b=",b)

P77 区间测速

s=25 t=int(input("请输入用时(秒):")) v=s*3600/t if v> from math import sqrt >>> sqrt(9) 3.0

P86 计算圆的面积

import math r=float(input("请输入圆的半径r:")) pi=math.pi s=pi*pow(r, 2) print("圆面积是:",str(s))

P86 随机出场顺序

import random cla=["(2)班","(3)班","(5)班","(8)班","(9)班"] random.shuffle(cla) for x in cla: print(x)

P86 使用Image模块操作图像

from PIL import Image im= Image.open("school.jpg") #打开school.jpg图像文件 print(im.format) #获取图像文件格式 print(im.size) #获取图像尺寸大小(以像素为单位表示图像的宽度和高度) print(im.mode) #获取图像的颜色模式 im.rotate(45).show() #将图像旋转45°后显示

* P87 实践与体验 编程实现图像的简单处理

from PIL import Image import numpy as np import matplotlib. pyplot as plt img=np.array(Image.open('lena.jpg').convert('L')) rows, cols=img.shape #图像尺寸分别赋值 for i in range(rows): #依次取每个像素的坐标 for j in range(cols): if(img[i,j]>128): #像素值大于128,赋值1,否则为0 img[i,j]=1 else: img[i,j]=0 plt.figure("lena") #指定当前绘图对象 plt.imshow(img,cmap='gray') #显示灰度图像 plt.axis('off') #关闭图像坐标 plt.show() #弹出包含了图片的窗口

P88 思考与练习1 表达式或程序语句的值

(1)123%100 (2)len("Hello Leo!") (3)abs(-12) (4)data=[172,9,165,29,156,21] max(data)

P89 思考与练习6 turtle画图

import turtle t=turtle.Pen() turtle.bgcolor("white") colors=["red","green","blue","yellow"] for x in range(100): t.pencolor(colors[x%4]) t.circle(x) t.left(91) 3.3 简单算法及其程序实现

P91 根据灰度值判断黑白

R=43 G=10 B=241 Gray_scale=0.299*R+0.587*G+0.114*B if Gray_scale f = open('test.txt','r') >>> f.read() 'Hello, world!'

调用open()函数打开由参数指定的文件对象,参数'r'表示读文本文件模式,参数'w'表示写文本文件模式,'r+'模式则表示在打开一个文本文件同时允许读和写。调用read()函数会一次性读取文件的全部内容

for line in f.readlines(): print(line.strip()) #strip()把末尾的'\n'删掉

文件使用完毕后必须关闭,操作系统才会把内存中的待写入的数据全部写入磁盘

>>> f.close()

将"Hello, world!"写入test.txt

>>> f = open('test.txt','w') >>> f.write('Hello, world!') >>> f.close()

P94 自定义判断黑白函数

def bw_judge(R,G,B): Gray_scale=0.299*R+0.587*G+0.114*B if Gray_scale=width*height*0.64: print("已填涂!") else: print("未填涂!")

P97 准考证填涂识别

def bw_judge(R, G, B): # bw_judge用于判断一个像素的填涂情况 Gray_scale = 0.299 * R + 0.587 * G + 0.114 * B return Gray_scale < 132 def fill_judge(x, y): # fill_judge用于判断信息点的填涂情况 count = 0 for i in range(x, x + fill_width + 1): for j in range(y, y + fill_height + 1): R, G, B = pixels[i, j] if bw_judge(R, G, B) == True: count = count + 1 if count >= fill_width * fill_height * 0.64: return True from PIL import Image x_start = 12 # 起始点坐标 y_start = 92 fill_width = 24 # 信息点宽度 fill_height = 12 # 信息点高度 space_width = 16 # 间隔宽度 space_height = 15 # 间隔高度 num_length = 9 # 准考证号长度 total_width = fill_width + space_width total_height = fill_height + space_height image = Image.open("fill.bmp") pixels = image.load() number = "" for col in range(num_length): # x从左至右,y从上至下对填涂区进行检测 for row in range(10): x = x_start + total_width * col y = y_start + total_height * row if fill_judge(x, y) == True: number = number + str(row) break else: # 10个信息点检测完毕后未发现有填涂 number = number + '#' print(number)

* P99 实践与体验 图像字符画

from PIL import Image serarr=['@','#','$','%','&','?','*','o','/','{','[','(','|','!','^','~','-','_',':',';',',','.','`',' '] count=len(serarr) def toText(image_file): asd ='' # 储存字符串 for h in range(0, image_file.size[1]): # 垂直方向 for w in range(0, image_file.size[0]): # 水平方向 r,g,b =image_file.getpixel((w,h)) gray =int(r* 0.299+g* 0.587+b* 0.114) asd=asd+serarr[int(gray/(255/(count-1)))] asd=asd+'\r\n' return asd image_file = Image.open("boy.jpg") # 打开图片 image_file=image_file.resize((int(image_file.size[0]*0.9), int(image_file.size[1]*0.5))) #调整图片大小 tmp=open('boy.txt','a') tmp.write(toText(image_file)) tmp.close() 第四章 数据处理与应用 4.1 常用表格数据的处理 4.2 大数据处理

P114 统计文件filenmae中各单词出现的频率

wordcount={} for word in open(filename,'r').read(): wordcount[word]+=1

P120 例1 创建1个seris结构类型的对象s1,存储3名同学的身高值

import pandas as pd s1=pd.Series([166,178,180]) print(s1) #创建Series对象时指定索引 s2=pd.Series([166,178,180],index=["s01","s02","s03"]) print(s2)

P121 例2 查看例1中s1对象的index、values属性值

for i in s1.index: print(i) for i in s1.values: print(i) for i in s1: print(i)

P121 例3 使用相同长度的列表字典构建一个DataFrame对象df1,存储3名同学的姓名、性别、图书借阅次数数据。

import pandas as pd data={"姓名":["王静怡","张佳妮","李辰武"],"性别":["女","女","男"],"借阅次数":[28,56,37]} df1=pd.DataFrame(data,columns=["姓名","性别","借阅次数"]) print(df1)

P121 例4 读取Excel文件“test.xlsx”中的数据,创建DataFrame对象df。

import pandas as pd df=pd.read_excel("test.xlsx") print(df)

P122 例5 查看df1对象的索引、列标题、值,并将行列转置。

for i in df1.index: print(i) for i in df1.columns: print(i) for i in df1.values: print(i) print(df1.T)

P122 例6 分别检索df1对象中“姓名”“借阅次数”列数据,并修改“借阅次数”列数据

print(df1.姓名) print(df1["借阅次数"]) df1.借阅次数=[30,52,68] print(df1)

P123 例7 对df对象中的数据进行以下编辑:在最后一行追星一行数据;删除“规格”列数据;删除第一行数据。

#添加一行数据 df_add=df.append({"地区":"石家庄市","规格":"红富士 一级","单位":"元/500克","价格":4.00,"采价点":"集市3","采集时间":"11月中旬"},ignore_index=True) df_delc=df.drop("规格",axis=1) #删除"规格"列数据 df_delr=df.drop(0) #删除第1行数据

P124 例8 将df对象中的数据按“地区”分组,并计算分组后各组数据的平均值。

g=df.groupby("地区",as_index=False) print(g.mean()) #计算每组价格数据的平均值

P124 例9 对df对象中的数据,按“价格”值降序排序。

df_sort=df.sort_values("价格",ascending=False) #按价格值降序排序 print(df_sort)

P125 例10 绘制正弦曲线图。

import numpy as np import matplotlib.pyplot as plt x=np.linspace(0,10,1000) y1=np.sin(x) y2=np.sin(x**2) plt.figure(figsize=(8,4)) #创建图表对象 plt.title("sin(x) and sin(x**2)") #设置图表标题文字 plt.plot(x,y1,label="sin(x)",color="r",linewidth=2) #绘制线形图 plt.scatter(x, y2,label="sin(x**2)") #绘制散点图 plt.ylim(-1.5,1.5) #设置y坐标轴取值范围 plt.xlim(0,10) #设置x坐标轴取值范围 plt.legend() #显示图例 plt.show()

P126 通过统计某地姓名数据,分析当地姓氏的构成情况。

import pandas as pd import matplotlib.pyplot as plt import codecs #处理中文utf-8编码 from matplotlib.font_manager import FontProperties #显示中文字体 file = codecs.open('names.csv',"r","utf-8") #打开文件 # 定义复姓 list fx=['欧阳','太史','端木','上官','司马','东方','独孤','南宫','万俟','闻人','夏侯','诸葛','尉迟','公羊', '赫连','澹台','皇甫','宗政','濮阳','公冶','太叔','申屠','公孙','慕容','仲孙','钟离','长孙','宇文', '司徒','鲜于','司空','闾丘','子车','亓官','司寇','巫马','公西','颛孙','壤驷','公良','漆雕','乐正', '宰父','谷梁','拓跋','夹谷','轩辕','令狐','段干','百里','呼延','东郭','南门','羊舌','微生','公户', '公玉','公仪','梁丘','公仲','公上','公门','公山','公坚','左丘','公伯','西门','公祖','第五','公乘' ] xing = [] j=0 for line in file: if line[0:2] in fx: #取复姓 xing.append(line[0:2]) else: xing.append(line[0:1]) #取单姓 j=j+1 data={'xing':xing,"renshu":0} df=pd.DataFrame(data) #构造DataFrame数据结构 s= df.groupby('xing').count() #按照"xing"分组计数 s=s.sort_values('renshu',ascending=False) #按照"renshu"降序排列 ax=s[0:20].plot(kind='bar',rot=0) #对前20绘图 #显示中文标签 font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14) for label in ax.get_xticklabels(): label.set_fontproperties(font) plt.show() #显示图形 print(s)

本代码出现了codecs模块,是为了处理中文编码的。如果报错把codecs.py复制到当前文件夹或者添加Pythob Lib文件夹的环境变量。

* P132 实践与体验 中文分词与标签云

import os import numpy as np from PIL import Image import matplotlib.pyplot as plt from wordcloud import WordCloud,STOPWORDS d = os.path.dirname(__file__) #d取当前文件路径 pic="alice_mask.png" #pic存放图片名称 pic_mask = np.array(Image.open(os.path.join(d, pic))) wc = WordCloud(background_color="white", max_words=6000, mask=pic_mask, stopwords=STOPWORDS,font_path="fonts/simhei.ttf") wc.fit_words(wf) #生成标签云,wf存放词语及词频 plt.imshow(wc) #显示图片

P138 思考与练习 使用Python中文分词模块jieba,体验中文分词

import jieba #引用jieba分词模块 text = open('file_name.txt','r').read() #读入文本文件 seg_list = jieba.cut(str_delete,cut_all=True) #全模式分词 print("全模式分词:"," ".join(seg_list)) seg_list = jieba.cut(text) #默认模式分词 print("全模式分词:"," ".join(seg_list)) 4.3 大数据典型应用

* P142 实践与体验 出租车轨迹可视化分析

import matplotlib.pyplot as plt def plot_file (file): #绘制每个文件的GPS坐标轨迹 i=0 jd=[] #经度 wd= [] #纬度 for line in open (file) : i=i+1 #切分行数据 splitline=line.split(',') #取轨迹坐标 x=float(splitline[4]) y=float(splitline[5]) jd.append(x) wd.append(y) plt.plot(jd,wd) #画点 filename='xyz.txt' plot_file(filename) plt.show() 第五章 人工智能及应用 5.1 人工智能的产生与发展 5.2 人工智能的应用 5.3 人工智能对社会的影响


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3