慕的地6264312
2023-09-26 14:57:28
我最近獲取了當地健身房的數據,我正在嘗試對數據進行標準化,以便可以創建一個“健身房注冊”對象,其中包含注冊該會話的所有人員。文本文件如下所示:Sep 30th? '20 at 9:00AM Until Sep 30th? '20 at 10:00AMJD? John Doe? ??AW? Alice Wonderland? ??IM? Iron ManSep 30th? '20 at 8:00AM Until Sep 30th? '20 at 9:00AMJD? John Doe? ??AW? Alice Wonderland? ??IM? Iron Man我已經能夠使用 pandas 按列 [姓名首字母,姓名] 分隔注冊,但我不知道如何檢測何時一行對應于時間段而不是注冊的人。因此,程序運行后,每一行都應包含 [姓名首字母、姓名、時間段] 列對我來說處理這些數據最簡單的方法就是采用這種格式,JD? John Doe? ? Sep 30th? '20 at 9:00AM Until Sep 30th? '20 at 10:00AMAW? Alice Wonderland? ? Sep 30th? '20 at 9:00AM Until Sep 30th? '20 at 10:00AMIM? Iron Man? ? Sep 30th? '20 at 9:00AM Until Sep 30th? '20 at 10:00AMJD? John Doe? ? Sep 30th? '20 at 8:00AM Until Sep 30th? '20 at 9:00AMAW? Alice Wonderland? ? Sep 30th? '20 at 8:00AM Until Sep 30th? '20 at 9:00AMIM? Iron Man? ? ? Sep 30th? '20 at 8:00AM Until Sep 30th? '20 at 9:00AM我嘗試遍歷每一行,一旦出現一個時隙行,我就會將該行附加到下一行,直到出現新的時隙。def testSort():? ? with open("1-weak-gym.txt") as fp:? ? ? ? id= []? ? ? ? totalSheet=[]? ? ? ? timeSlot = []? ? ? ? lastLine=[]? ? ? ? for ln in fp:? ? ? ? ? ? if ln.startswith("Sep"): ##this is a time slot? ? ? ? ? ? ? ? timeSlot.clear()? ? ? ? ? ? ? ? timeSlot.append(ln[0:]) ##save that time slot as the lastDate variable? ? ? ? ? ? else:? ? ? ? ? ? ? ? if (timeSlot):? ? ? ? ? ? ? ? ? ? totalSheet.append(timeSlot) ##append the time slot? ? ? ? ? ? ? ? ? ? totalSheet.append(ln[0:]) ##append the name line? ? ? ? ? ? ? ? else:? ? ? ? ? ? ? ? ? ? print('Hello eror')? ? print(totalSheet, file=open("newOuput.txt","a"))?
1 回答

慕少森
TA貢獻2019條經驗 獲得超9個贊
您可以嘗試這種方法(如果標題行末尾的時間有很強的模式):
import re
def is_time_format(s):
time_re = re.compile(r'\b((1[0-2]|0?[1-9]):([0-5][0-9])([AaPp][Mm]))')
return bool(time_re.match(s))
with open("1-weak-gym.txt") as fp:
new_lines = []
extra_info = ''
for line in fp:
last_bit = line.split(' ')[-1]
if is_time_format(last_bit):
extra_info = line
continue
else:
new_lines.append(line.rstrip() + '\t' + extra_info)
open("newOutput", 'w').writelines(new_lines)
然后您將獲得正確格式的文件。
添加回答
舉報
0/150
提交
取消