У меня есть .txt, заполненный данными, которые я хочу фильтровать (около 5800 строк), поскольку некоторые строки встречаются как дубликаты с той лишь разницей, что временная метка ровно через 2 часа. Те строки, которые являются поздней версией дубликата (например, первая строка в приложенном примере), должны быть опущены. Все остальные строки должны быть оставлены и записаны в новый .txt-файл.Удаление дубликатов из файла .txt и создание нового .txt-файла
1_3_IMM 2016-07-19 16:11:56 00:00:40 2 Sensor Check # should go
1_3_IMM 2016-07-19 14:12:40 00:00:33 2 Sensor Check # should stay
1_3_IMM 2016-07-19 14:11:56 00:00:40 2 Sensor Check # should stay
1_3_IMM 2016-07-19 16:12:40 00:00:33 2 Sensor Check # should go
1_4_IMM 2016-07-19 17:23:25 00:00:20 2 Sensor Check # should stay
1_4_IMM 2016-07-19 19:23:25 00:00:20 2 Sensor Check # should go
1_4_IMM 2016-07-19 19:15:24 00:02:21 2 Sensor Check # should stay
1_4_IMM 2016-07-19 19:25:13 00:02:13 2 Sensor Check # should stay
Я написал код в Python, выход представляет собой файл .txt с только 1 строка текста:
deleted
Я не могу показаться, чтобы решить эту. Вы можете помочь? См. Код ниже.
import os
def filter_file():
with open("output.txt", "w") as output:
#open the input file from a specified directory
directory = os.path.normpath("C:/Users/sande_000/Documents/Python files")
for subdir, dirs, files in os.walk(directory):
for file in files:
if file.startswith("input"):
input_file=open(os.path.join(subdir, file))
#iterate over each line of the file
for line in input_file:
machine = line[0:7] #stores machine number
date = line[8:18] #stores date stamp
time_1 = int(line[19:21]) #stores hour stamp
time_2 = int(line[22:24]) #stores minutes stamp
time_3 = int(line[25:27]) #stores second stamp
#check current line with other lines for duplicates by iterating over each line of the file
for otherline in input_file:
compare_machine = otherline[0:7]
compare_date = otherline[8:18]
compare_time_1 = int(otherline[19:21])+2
compare_time_2 = int(otherline[22:24])
compare_time_3 = int(otherline[25:27])
#check whether machine number & date/hour+2/minutes/seconds stamp are similar.
#If yes, write 'deleted' to output.txt and stop comparing lines.
#If no, continue with comparing next line.
if compare_machine == machine and compare_date == date and compare_time_1 == time_1 and compare_time_2 == time_2 and compare_time_3 == time_3:
output.write("deleted"+"\n")
break
else:
continue
#If no overlap between one line with any other line from the file, write that line to output.txt since it is no duplicate.
output.write(line)
input_file.close()
if __name__ == "__main__":
filter_file()
Конечно '14: 12: 40' должен остаться и' 16: 12: 40' должен идти, не так ли? У вас все наоборот. – Tagc
В вашем текстовом файле нет логики. Как только предыдущий должен пойти, а для другого - раньше. Кроме того, ваш файл журнала не сортируется по дате. Означает ли порядок? –
Это действительно было ошибкой, текстовый файл должен быть логичным. Для всей ясности: раньше нужно было оставаться, а потом идти. Это правда, что файл журнала не сортируется по дате, я ничего не могу с этим поделать. – Sander