【旧文更新】武汉光迅科技22校招笔试Python题改进(增加GUI) 基于Python的125温度传感器模块数据处理

发布于:2024-06-04 ⋅ 阅读:(126) ⋅ 点赞:(0)

【旧文更新】武汉光迅科技22校招笔试Python题改进(增加GUI)
基于Python的125温度传感器模块数据处理

关于旧文新发

为何要进行旧文新发?
因为我在2023年博客之星评选中发现 有的人转载、抄袭他人文章 稍微改动几下也能作为高质量文章入选
所以我将把我的旧文重新发一次 然后也这样做

2023年博客之星规则:
在这里插入图片描述

题目分析

原本的基础代码:

blog.csdn.net/weixin_53403301/article/details/120912722

原资源:

download.csdn.net/download/weixin_53403301/33844279

现资源:

download.csdn.net/download/weixin_53403301/35432848

题目要求:

  1. 输入数据: 见附件 <125模块温度查询数据.txt>

    #号开头的是命令, #号的下一行是命令应答内容

  2. 输出结果:提取指定字段的值,输出到文件 <125温度统计.txt>
    即上图中01 f1 字段,对应每条应答消息的倒数第5和第4个字节。
    497
    497
    497
    497

    在这里插入图片描述

  3. 根据 步骤2的结果数据,并用Python 输出图谱
    在这里插入图片描述
    直接上代码:

# -*- coding: utf-8 -*-
"""
Created on Fri Oct 22 17:44:48 2021

@author: 16016
"""
# Python 3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit (AMD64)] :: Anaconda, Inc. on win32
# matplotlib.__version__ == 2.2.3

import matplotlib.pyplot as plt # 调用matplotlib绘图库
plt.rcParams['font.sans-serif'] = ['SimHei'] # 载入字体
plt.rcParams['figure.figsize'] = (10.0, 10.0) # 设置大小 单位英寸
import time # 调用系统时间库
import os # 调用系统控制库
import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import *
import tkinter.messagebox
from PIL import Image, ImageTk 
from shutil import copyfile

def removeCharterLine(path1, path2): # 读取温度文档文件 去除#符号 并保存在临时文件中
    f = open(path1, 'r')
    f2 = open(path2, 'w')

    for i in f:
        if not i.strip().startswith("#"):
            f2.write(i)

    f.close()
    f2.close()

def removeBlock(path1,path2): # 读取第一个临时文件 去除空行 并保存在临时文件2中
    with open(path1,'r',encoding = 'utf-8') as fr,open(path2,'w',encoding = 'utf-8') as fd:
        for text in fr.readlines():
            if text.split():
                fd.write(text)
                fr.close
                fd.close
                        
def transData(path1,path2,path3): # 读取 临时文件2 输出温度文档文件和临时文件3
    # 将临时文件2中的每一行的数据用空格分开 提取第11和12个数据 并将其由字符串类型转为16进制整型 再转换为10进制
    # 将十进制数据保存在输出温度文档文件中
    # 将输出温度文档中的数据每一行前面都加上序号 代表第x个数据 保存在临时文件3中 并返回数据总数+1
    file1 = open(path1,'r')
    file2 = open(path2,'w')
    file3 = open(path3,'w')
    count = int()
    count = 1
    for line in file1.readlines():
        curLine=line.strip().split(" ")    
        hexData=curLine[11]+curLine[12]
        decData=int(hexData,16)
        strData=str(decData)
        file2.write(strData+"\n")
        file3.write(str(count)+' '+strData[0]+strData[1]+'.'+strData[2]+"\n")
        count=count+1
    file1.close
    file2.close
    file3.close
    return count

def drawData(path1,i,minTemp,maxTemp): # 读取临时文件3 将每一行用空格分开 xy坐标值对应第0、1数据
    # 输入参数i表示数据总数(x轴)+1的值
    # 输出参数minTemp和maxTemp表示最低、最高温度范围 用于调整y轴比例
    input_txt = path1
    x = []
    y = []
    
    f = open(input_txt,'r')
    
    for line in f:
        line = line.strip('\n')
        line = line.split(' ')
    
        x.append(float(line[0]))
        y.append(float(line[1]))
        if float(line[1]) > maxTemp:
            print("最高温度设置过低")
            return 0
        if float(line[1]) < minTemp:
            print("最低温度设置过高")
            return 0
    
    f.close
    j=int(i/4//100*100)
    k=float((maxTemp-minTemp)/5)
    plt.plot(x, y, '-',marker=',', markersize = '1')
    plt.grid() # 显示网格线
    plt.xticks([0,j,j*2,j*3,j*4,i])
    plt.yticks([minTemp,minTemp+k,minTemp+2*k,minTemp+3*k,minTemp+4*k,maxTemp])
    plt.xlabel('x')
    plt.ylabel("temp")
    plt.title("temp")
    plt.tick_params(axis="both")
    temp_pic="temp("+str(minTemp)+"°C-"+str(maxTemp)+"°C)["+str(time.strftime('%Y-%m-%d %H-%M-%S', time.localtime()))+"].png"
    plt.savefig(temp_pic)
    plt.show()
    return temp_pic

def addData(path1,i): #可省略 增加第一行的 0 0数据 和最后一行的2155 100数据
    
    fp = open(path1)           #指定文件
    s = fp.read()                   #将指定文件读入内存
    fp.close()                      #关闭该文件
    a = s.split('\n')
    a.insert(0, '0 0')    #在第 0行插入
    s = '\n'.join(a)                #用'\n'连接各个元素
    fp = open(path1, 'w')
    fp.write(s)
    fp.close()
    
    f=open(path1,"a")
    f.write(str(i)+' 100') # 将温度值100及其序号写入最后一行
    f.close()
    
def txt_All(path1,minTemp,maxTemp):
    filepath1=path1
    filepath2='./125温度统计.txt'
    tempfile1='./new1.txt'
    tempfile2='./new2.txt'
    tempfile3='./new3.txt'
    removeCharterLine(filepath1,tempfile1)          # 删除#符号             
    removeBlock(tempfile1,tempfile2)                # 删除空行
    os.remove(tempfile1) # 删除临时文档文件
    Count=transData(tempfile2,filepath2,tempfile3)  # 输出温度数据 给数据增加序号并输出临时文件 获取数据总数+1的值
#    addData(tempfile3,Count) #可省略 增加第一行的 0 0数据 和最后一行的2155 100数据
    os.remove(tempfile2) # 删除临时文档文件
    temp_pic=drawData(tempfile3,Count,minTemp,maxTemp) # 画坐标图 输入读取文件 数据总数+1的值 和 最低、最高温度值
    # 删除临时文档文件
    os.remove(tempfile3)
    return temp_pic

if __name__ == '__main__':  
    root=Tk()
    root.title("125模块温度数据处理")
    mainfram=Frame(root,width=700, height=150)
    mainfram.grid_propagate(0)
    mainfram.grid()
#    fram=Frame(mainfram,width=640, height=480)
#    fram.grid_propagate(0)
#    fram.grid()    
    
    minTemp = float(0)
    maxTemp = float(100)

    e1 = Entry(mainfram)
    e1.grid(ipadx=200,row=0,column=0)
    e1.delete(0, END)  # 将输入框里面的内容清空
    e1.insert(0, '125模块温度查询数据.txt')  
    
    e2 = Entry(mainfram)
    e2.grid(ipadx=200,row=1,column=0)
    e2.delete(0, END)  # 将输入框里面的内容清空
    e2.insert(0, '请选择125模块温度查询数据的对应文件')
    
    e3 = Entry(mainfram)
    e3.grid(ipadx=200,row=2,column=0)
    e3.delete(0, END)  # 将输入框里面的内容清空
    e3.insert(0, '0')  
    
    e4 = Entry(mainfram)
    e4.grid(ipadx=200,row=3,column=0)
    e4.delete(0, END)  # 将输入框里面的内容清空
    e4.insert(0, '100')
    
    selectPath=""
    
#    img = Image.open("temp(0°C-100°C).png")
#    tkimg = ImageTk.PhotoImage(image=img)
#    image_ctl = tk.Label(fram, image=tkimg)
#    image_ctl.pack(side=BOTTOM, fill=tk.Y, expand=1)
    
    def get_mixTemp():
        new_mixTemp=float(e3.get())
        print('最低温度:',new_mixTemp)
        return new_mixTemp
    
    def get_maxTemp():
        new_maxTemp=float(e4.get())
        print('最高温度:',new_maxTemp)
        return new_maxTemp
    
    def save_pic_as():
        global selectPath
        print("请选择保存文件的路径,关闭程序后将自动保存在所选目录")
        selectPath = askdirectory(title="请选择保存文件的路径,关闭程序后自动保存")
        
    def save_pic():
        global selectPath
        print("关闭程序后将自动保存在当前目录")
        selectPath = os.getcwd()
        
    def tk_pic_show(temp_pic):
        global selectPath
        print("已保存临时图像文件:"+temp_pic)        
        top=Toplevel()
        top.title("125模块温度数据坐标图")
        picfram=Frame(top,width=720, height=720)
        picfram.grid_propagate(0)
        picfram.grid() 
        img = Image.open(temp_pic)
        tkimg = ImageTk.PhotoImage(image=img)
        image_ctl = tk.Label(picfram, image=tkimg)
        image_ctl.pack()
        button_save=Button(picfram,width=50,text="保存图片",command=save_pic).grid(row=0,column=0)
        button_save_as=Button(picfram,width=50,text="另存图片",command=save_pic_as).grid(row=0,column=1)        
        top.mainloop()
        if selectPath:
            save_file = selectPath+"/"+temp_pic
            save_file_list = save_file.split(".png")
            save_file_name = save_file_list[0]+"SA.png"
            copyfile(temp_pic, save_file_name)
#            os.system("copy "+temp_pic+" "+selectPath+"/"+temp_pic)
            print("已保存图像到:"+save_file_name)
            save_file_name = ""
            selectPath = ""
            save_file_list = []
            save_file = ""
            if os.path.isfile(temp_pic):
                os.remove(temp_pic)
                print("已删除临时图像文件:"+temp_pic)
        else:
            selectPath = ""
            if os.path.isfile(temp_pic):
                os.remove(temp_pic)
                print("已删除临时图像文件:"+temp_pic)

        
    def filedeal():
        minTemp = get_mixTemp()
        maxTemp = get_maxTemp()
        if minTemp > maxTemp:
            print("最低温度不得大于最高温度")
        else:
            temp_pic=txt_All('125模块温度查询数据.txt',minTemp,maxTemp)
            e1.delete(0, END)  # 将输入框里面的内容清空
            e1.insert(0, '125模块温度查询数据.txt')
            if temp_pic == 0:
                print("温度设置有误")
            else:
                tk_pic_show(temp_pic)
        
    def filefound():
        minTemp = get_mixTemp()
        maxTemp = get_maxTemp()
        if minTemp > maxTemp:
            print("最低温度不得大于最高温度")
        else:
            filepath= askopenfilename(title="请选择125模块温度查询数据的对应文件", filetypes=[("文本文件(*.txt)", "*.txt"),("所有文件(*.*)", "*.*")])
    #        print (filepath)
            temp_pic=txt_All(filepath,minTemp,maxTemp)
            e2.delete(0, END)  # 将输入框里面的内容清空
            e2.insert(0, filepath)
            if temp_pic == 0:
                print("温度设置有误")
            else:
                tk_pic_show(temp_pic)        

    

    button1=Button(mainfram,width=20,text="当前目录下直接处理",command=filedeal).grid(row=0,column=1)
    button2=Button(mainfram,width=20,text="选择文件处理",command=filefound).grid(row=1,column=1)
    button3=Button(mainfram,width=20,text="更改坐标图最低温度/°C",command=get_mixTemp).grid(row=2,column=1)
    button4=Button(mainfram,width=20,text="更改坐标图最高温度/°C",command=get_maxTemp).grid(row=3,column=1)
    #print (fram.size())

    root.mainloop()

运行效果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

附录:列表的赋值类型和py打包

列表赋值

BUG复现

闲来无事写了个小程序 代码如下:

# -*- coding: utf-8 -*-
"""
Created on Fri Nov 19 19:47:01 2021

@author: 16016
"""

a_list = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15']
#print(len(a_list))
#b_list = ['','','','','','','','','','','','','','','','']
c_list = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
#for i in range(16):
if len(a_list):
    for j in range(16):
        a_list[j]=str(a_list[j])+'_'+str(j)
        print("序号:",j)
        print('a_list:\n',a_list)
        
        
        c_list[j]=a_list
        print('c_list[0]:\n',c_list[0])
        print('\n')
#        b_list[j]=a_list[7],a_list[8]
#        print(b_list[j])
        # 写入到Excel:
#print(c_list,'\n')    

我在程序中 做了一个16次的for循环 把列表a的每个值后面依次加上"_"和循环序号
比如循环第x次 就是把第x位加上_x 这一位变成x_x 我在输出测试中 列表a的每一次输出也是对的
循环16次后列表a应该变成[‘0_0’, ‘1_1’, ‘2_2’, ‘3_3’, ‘4_4’, ‘5_5’, ‘6_6’, ‘7_7’, ‘8_8’, ‘9_9’, ‘10_10’, ‘11_11’, ‘12_12’, ‘13_13’, ‘14_14’, ‘15_15’] 这也是对的

同时 我将每一次循环时列表a的值 写入到空列表c中 比如第x次循环 就是把更改以后的列表a的值 写入到列表c的第x位
第0次循环后 c[0]的值应该是[‘0_0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘10’, ‘11’, ‘12’, ‘13’, ‘14’, ‘15’] 这也是对的
但是在第1次循环以后 c[0]的值就一直在变 变成了c[x]的值
相当于把c_list[0]变成了c_list[1]…以此类推 最后得出的列表c的值也是每一项完全一样
我不明白这是怎么回事
我的c[0]只在第0次循环时被赋值了 但是后面它的值跟着在改变

如图:
在这里插入图片描述
第一次老出bug 赋值以后 每次循环都改变c[0]的值 搞了半天都没搞出来
无论是用appen函数添加 还是用二维数组定义 或者增加第三个空数组来过渡 都无法解决

代码改进

后来在我华科同学的指导下 突然想到赋值可以赋的是个地址 地址里面的值一直变化 导致赋值也一直变化 于是用第二张图的循环套循环深度复制实现了

代码如下:

# -*- coding: utf-8 -*-
"""
Created on Fri Nov 19 19:47:01 2021

@author: 16016
"""

a_list = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15']
#print(len(a_list))
#b_list = ['','','','','','','','','','','','','','','','']
c_list = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
#for i in range(16):
if len(a_list):
    for j in range(16):
        a_list[j]=str(a_list[j])+'_'+str(j)
        print("序号:",j)
        print('a_list:\n',a_list)
        
        
        for i in range(16):
            c_list[j].append(a_list[i])
        print('c_list[0]:\n',c_list[0])
        print('\n')
#        b_list[j]=a_list[7],a_list[8]
#        print(b_list[j])
        # 写入到Excel:
print(c_list,'\n')    

解决了问题

在这里插入图片描述

优化

第三次是请教了老师 用copy函数来赋真值

代码如下:

# -*- coding: utf-8 -*-
"""
Created on Fri Nov 19 19:47:01 2021

@author: 16016
"""

a_list = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15']
#print(len(a_list))
#b_list = ['','','','','','','','','','','','','','','','']
c_list = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
#for i in range(16):
if len(a_list):
    for j in range(16):
        a_list[j]=str(a_list[j])+'_'+str(j)
        print("序号:",j)
        print('a_list:\n',a_list)
        
        
        c_list[j]=a_list.copy()
        print('c_list[0]:\n',c_list[0])
        print('\n')
#        b_list[j]=a_list[7],a_list[8]
#        print(b_list[j])
        # 写入到Excel:
#print(c_list,'\n')    

同样能解决问题
在这里插入图片描述
最后得出问题 就是指针惹的祸!

a_list指向的是个地址 而不是值 a_list[i]指向的才是单个的值 copy()函数也是复制值而不是地址

如果这个用C语言来写 就直观一些了 难怪C语言是基础 光学Python不学C 遇到这样的问题就解决不了

C语言yyds Python是什么垃圾弱智语言

总结

由于Python无法单独定义一个值为指针或者独立的值 所以只能用列表来传送
只要赋值是指向一个列表整体的 那么就是指向的一个指针内存地址 解决方法只有一个 那就是将每个值深度复制赋值(子列表内的元素提取出来重新依次连接) 或者用copy函数单独赋值

如图测试:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
部分代码:

# -*- coding: utf-8 -*-
"""
Created on Sat Nov 20 16:45:48 2021

@author: 16016
"""

def text1():
    A=[1,2,3]
    B=[[],[],[]]
    for i in range(len(A)):
        A[i]=A[i]+i
        B[i]=A
        print(B)

def text2():
    A=[1,2,3]
    B=[[],[],[]]
    
    A[0]=A[0]+0
    B[0]=A
    print(B)
    A[1]=A[1]+1
    B[1]=A
    print(B)
    A[2]=A[2]+2
    B[2]=A
    print(B)
    
if __name__ == '__main__':
    text1()
    print('\n')
    text2()

py打包

Pyinstaller打包exe(包括打包资源文件 绝不出错版)

依赖包及其对应的版本号

PyQt5 5.10.1
PyQt5-Qt5 5.15.2
PyQt5-sip 12.9.0

pyinstaller 4.5.1
pyinstaller-hooks-contrib 2021.3

Pyinstaller -F setup.py 打包exe

Pyinstaller -F -w setup.py 不带控制台的打包

Pyinstaller -F -i xx.ico setup.py 打包指定exe图标打包

打包exe参数说明:

-F:打包后只生成单个exe格式文件;

-D:默认选项,创建一个目录,包含exe文件以及大量依赖文件;

-c:默认选项,使用控制台(就是类似cmd的黑框);

-w:不使用控制台;

-p:添加搜索路径,让其找到对应的库;

-i:改变生成程序的icon图标。

如果要打包资源文件
则需要对代码中的路径进行转换处理
另外要注意的是 如果要打包资源文件 则py程序里面的路径要从./xxx/yy换成xxx/yy 并且进行路径转换
但如果不打包资源文件的话 最好路径还是用作./xxx/yy 并且不进行路径转换

def get_resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)

而后再spec文件中的datas部分加入目录
如:

a = Analysis(['cxk.py'],
             pathex=['D:\\Python Test\\cxk'],
             binaries=[],
             datas=[('root','root')],
             hiddenimports=[],
             hookspath=[],
             hooksconfig={},
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)

而后直接Pyinstaller -F setup.spec即可

如果打包的文件过大则更改spec文件中的excludes 把不需要的库写进去(但是已经在环境中安装了的)就行

这些不要了的库在上一次编译时的shell里面输出
比如:
在这里插入图片描述

在这里插入图片描述
然后用pyinstaller --clean -F 某某.spec

附录:关于旧文新发

为何要进行旧文新发?
因为我在2023年博客之星评选中发现 有的人转载、抄袭他人文章 稍微改动几下也能作为高质量文章入选
所以我将把我的旧文重新发一次 然后也这样做

2023年博客之星规则:

  1. 自2023年1月1日起算起,平均每周创作过至少一篇高质量且非付费专栏的原创文章即可入围。由于博客之星是年度评选,所以统计时间一直截止到2023年12月17日。
  2. 高质量博文为80分以上原创博文,质量分查询地址:https://www.csdn.net/qc
  3. 入围条件补充说明:当前的入围状态为动态,一旦未达到每周平均创作过至少一篇高质量且非付费专栏的原创文章入围资格将会跳出入围资格,若当前还未入围者通过后期创作也可入围,当下并非最终结果。

网站公告

今日签到

点亮在社区的每一天
去签到