txtファイルには2つの異なるタイプのデータがあります。パンダを使用して各行を相互作用させ、対応するデータを追加するにはどうすればよいですか。

mlabenski

最近、地元のジムのデータを取得しました。データを正規化して、そのセッションに登録したすべての人を含む「ジム登録」オブジェクトを作成できるようにしようとしています。

テキストファイルは次のようになります:https//pastebin.com/YcnSJiA7

Sep 30th  '20 at 9:00AM Until Sep 30th  '20 at 10:00AM
JD  John Doe    
AW  Alice Wonderland    
IM  Iron Man
Sep 30th  '20 at 8:00AM Until Sep 30th  '20 at 9:00AM
JD  John Doe    
AW  Alice Wonderland    
IM  Iron Man

パンダを使用して登録を列[名前のイニシャル、名前]で区切ることはできましたが、行が時間枠に対応し、登録者に対応していないことを検出する方法がわかりません。

したがって、プログラムの実行後、すべての行は列[名前、名前、タイムスロットのイニシャル]で構成されている必要があります。

このデータを操作する最も簡単な方法は、この形式です。


JD  John Doe    Sep 30th  '20 at 9:00AM Until Sep 30th  '20 at 10:00AM
AW  Alice Wonderland    Sep 30th  '20 at 9:00AM Until Sep 30th  '20 at 10:00AM
IM  Iron Man    Sep 30th  '20 at 9:00AM Until Sep 30th  '20 at 10:00AM
JD  John Doe    Sep 30th  '20 at 8:00AM Until Sep 30th  '20 at 9:00AM
AW  Alice Wonderland    Sep 30th  '20 at 8:00AM Until Sep 30th  '20 at 9:00AM
IM  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")) 
スズメ

このアプローチを試すことができます(ヘッダー行の終わりに時間のある強いパターンがある場合):

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)

次に、適切な形式のファイルを取得します。

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

Related 関連記事

ホットタグ

アーカイブ