我试图弄清楚如何使用python编写以下问题。假设我们在.txt文件中设置了以下数据:
datatype1 designator1 3:45:14AM
datatype1 designator1 3:45:19AM
datatype1 designator1 3:45:26AM
datatype1 designator1 3:45:31AM
datatype1 designator1 4:10:05AM
datatype1 designator1 4:10:21AM
datatype1 designator1 4:10:30AM
datatype1 designator1 4:10:46AM
注意时间休息。我需要我的代码来读取文本文件,并且在时间间隔中断时,将文件拆分并将以下内容写入另一个文本文件:
datatype1 designator1 3:45:14AM 3:45:31AM
datatype1 designator1 4:10:05AM 4:10:46AM
换句话说,我想将原始数据压缩到由开始和结束时间的单行代表的单个“会话”。
感谢您的帮助!
答案 0 :(得分:2)
执行以下步骤:
答案 1 :(得分:0)
您可以使用itertools.groupby
:
import itertools
file_data = [i.strip('\n').split() for i in open('filename.txt')]
final_data = [(a, list(b)) for a, b in itertools.groupby(file_data, key=lambda x:':'.join(x[-1].split(':')[:2]))]
new_final_data = [' '.join([' '.join(b[0][:-1]), ' '.join([b[0][-1], b[-1][-1]])]) for _, b in final_data]
print(new_final_data)
with open('filename.txt', 'a') as f:
f.write('\n'.join(new_final_data))
输出:
['datatype1 designator1 3:45:14AM 3:45:31AM', 'datatype1 designator1 4:10:05AM 4:10:46AM']
答案 2 :(得分:0)
使用pandas这个任务变得更具可读性:
import pandas as pd
import io
data = '''\
datatype1 designator1 3:30:14AM
datatype1 designator1 3:30:18AM
datatype1 designator1 3:45:14AM
datatype1 designator1 3:45:19AM
datatype1 designator1 3:45:26AM
datatype1 designator1 3:45:31AM
datatype1 designator1 4:10:05AM
datatype1 designator1 4:10:21AM
datatype1 designator1 4:10:30AM
datatype1 designator1 4:10:46AM'''
# Recreate dataset
df = pd.read_csv(io.StringIO(data),sep='\s+', header=None)
# Use this instead of above for real file
#df = pd.read_csv('path/to/file',sep='\s+', header=None)
# Get first and last by hour (convert to dt)
df[2] = sorted(pd.to_datetime(df[2]))
newdf = df.groupby((df[2].dt.hour, df[2].dt.minute // 15)).agg(['first', 'last'])
# Rename columns and drop duplicates
newdf.columns = list(range(len(newdf.columns)))
newdf.drop(newdf.columns[[1,3]], axis=1, inplace=True)
# Format time
newdf[[4,5]] = newdf[[4,5]].apply(lambda x: x.dt.strftime('%#H:%M:%S%p'))
# Output
print(newdf.to_csv('output.csv', index=False, header=False, sep=' '))
output.csv:
datatype1 designator1 3:30:14AM 3:30:18AM
datatype1 designator1 3:45:14AM 3:45:31AM
datatype1 designator1 4:10:05AM 4:10:46AM