基于Python的txt文本处理(武汉邮科院控股国企上市大厂Python面试题)
资源: https://download.csdn.net/download/weixin_53403301/33844279
题目要求:
-
输入数据: 见附件 <125模块温度查询数据.txt> #号开头的是命令, #号的下一行是命令应答内容 -
输出结果:提取指定字段的值,输出到文件 <125温度统计.txt> 即上图中01 f1 字段,对应每条应答消息的倒数第5和第4个字节。 497 497 497 497 … -
根据 步骤2的结果数据,并用Python 输出图谱
这里只用到了一个库 就是matplotlib 用于绘制最后的坐标图
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
直接上代码:
"""
Created on Fri Oct 22 17:44:48 2021
@author: 16016
"""
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
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):
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):
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):
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]))
f.close
j=int(i/4//100*100)
plt.plot(x, y, '-',marker=',', markersize = '1')
plt.xticks([0,j,j*2,j*3,j*4,i])
plt.yticks([0,20,40,60,80,100])
plt.xlabel('x')
plt.ylabel("temp")
plt.title("temp")
plt.tick_params(axis="both")
plt.show()
def addData(path1,i):
fp = open(path1)
s = fp.read()
fp.close()
a = s.split('\n')
a.insert(0, '0 0')
s = '\n'.join(a)
fp = open(path1, 'w')
fp.write(s)
fp.close()
f=open(path1,"a")
f.write(str(i)+' 100')
f.close()
if __name__ == '__main__':
filepath1='./125模块温度查询数据.txt'
filepath2='./125温度统计.txt'
tempfile='./new.txt'
tempfile2='./new2.txt'
tempfile3='./new3.txt'
removeCharterLine(filepath1,tempfile)
removeBlock(tempfile,tempfile2)
Count=transData(tempfile2,filepath2,tempfile3)
drawData(tempfile3,Count)
最后运行结果如下: 输入文件:125模块温度查询数据.txt
输出文件:125温度统计.txt
三个临时创建的txt文件:new.txt new2.txt new3.txt
|