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

武汉光迅科技22校招笔试Python题改进(增加GUI)——基于Python的125温度传感器模块数据处理,第1张

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

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

原本的基础代码:
https://blog.csdn.net/weixin_53403301/article/details/120912722?spm=1001.2014.3001.5501
原资源:
https://download.csdn.net/download/weixin_53403301/33844279

现资源:https://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()

运行效果:




欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/4830614.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-10
下一篇 2022-11-10

发表评论

登录后才能评论

评论列表(0条)

保存