1.以下数据格式第一列为时间,时间相同情况下,第二列数据需要递增,否则是错误的需要删除这一行数据
2.文本数据贴一部分:
16:28:34 3965 22 2 9
16:28:34 4165 22 1 8
16:28:34 4365 22 1 6
16:28:34 4568 22 2 9
16:28:34 4766 21 0 9
16:28:34 497 22 1 9
16:28:34 5166 22 1 9
16:28:34 5365 22 1 8
16:28:34 5565 23 0 9
16:28:34 5778 22 1 8
16:28:34 5965 22 2 9
16:28:34 6169 21 2 9
16:28:34 6365 21 1 9
16:28:34 657 21 1 9
16:28:34 6765 22 1 8
16:28:34 6966 22 2 9
16:28:34 7166 22 1 8
16:28:34 7365 22 1 9
3.我用列表方式读了这个数据,n行m列的列表,不过并没用,代码留做参考
F1 = open(r"C:\Users\11816\Desktop\data_clear.txt", "r")
List_row = F1.readlines()
list_source = []
#x = len(List_row)-1;
#y = len(List_row[0].split("\t"))-1;
for i in range(len(List_row)):
column_list = List_row[i].strip().split("\t") # 每一行split后是一个列表
list_source.append(column_list) # 加入list_source
print(list_source)#二元组
最后算法流程:逐行读取文本,符合要求打印,否则不打印,这样即可完成数据的过滤。
第一列时间的比较,如果格式符合 hh:mm:ss 的话直接用字符串比较即可。
最后再写回文件操作!
代码如下:
# encoding=utf8
path = "C:\\Users\\11816\\Desktop\\data_clear.txt"
f = open(path)
last_date = ""
last_num = 0
for line in f:
line = line.rstrip()
item = line.split("\t")#\t分隔
date = item[0]
num = float(item[1])
if date > last_date: # 直接比较即可,字符串比较原理
last_date = date
print(line)
with open("C:\\Users\\11816\\Desktop\\data_clear_last.txt", "a+") as f2:#以追加的方式
f2.write(line+"\n")# 写完通过\n进行换行
elif date == last_date:
if num > last_num:
last_num = num
print(line)
with open("C:\\Users\\11816\\Desktop\\data_clear_last.txt", "a+") as f2:
f2.write(line+"\n")# 写完通过\n进行换行