高中信息技術(Python) 必修1 數據與計算 源代碼


本文章原文地址: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 人工智能對社會的影響


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM