Разбор txt-файла по дате на 366 txt-файлов - PullRequest
0 голосов
/ 05 мая 2020

В настоящее время я выясняю, как разобрать текстовый файл на 366 отдельных файлов, например, Jan-1st.txt - De c -30th.txt (по одному на каждый день високосного года) и поместить соответствующую дату в этот txt файл. Однако я новичок только до python, поэтому я застрял. Сначала я начал с создания файлов за январь, но я хотел бы сделать это для всех месяцев в одном скрипте. Пока это мой код. Любая помощь / советы были бы великолепны!

import re


for month in Months:
    book = open("BookToParse.txt", "r")
    book = str(book.read())
    month = re.split(month, book, flags = re.IGNORECASE)
    month.pop(0)

for i in range(0, len(month)+1)
    writeBook = open("{}-Jan.txt".format(i), "w+")
    writeBook.write(month[i-1])
    writeBook.close()

Я вставлю ниже фрагмент из рассматриваемой книги

March 24th

  bla bla bla sometext here



March 25th

  Bla bla bla somemore text here


March 26th

 more text here...

Наконец, проанализированные файлы должны выглядеть как это; (cat Mar-25th.txt) Я не слишком требователен к соглашению об именах анализируемых файлов, если они являются последовательными.

March 25th

Bla Bla Bla

Я знаю, что этого относительно легко достичь, поэтому я обращаюсь к этому сообществу. Заранее благодарю вас за то, что уделили этому время, и я с нетерпением жду ваших ответов, A будет очень приветствоваться движение в правильном направлении.

1 Ответ

0 голосов
/ 05 мая 2020

Вот рабочий код. Объяснение находится в закомментированных строках.

months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
current_month = ""
current_date = ""

with open("BookToParse.txt", "r") as f:
    for line in f:
        if line.strip().split(" ")[0] in months: # Just extracting the month
            # Benefit of extracting the month and date makes it easier for file handling
            current_month = line.strip().split(' ')[0]
            current_date = line.strip().split(' ')[1]

        g = open(current_month + '-' + current_date + '.txt', "a+") # Opening the file in append mode, handles if the file does not exist or there are multiple lines for the date
        if line.strip().split(" ")[0] not in months: # We do not need the lines containing date. 
            g.write(line)
        g.close()

Вывод

$ cat March-24th.txt

  bla bla bla sometext here



$ cat March-25th.txt

  Bla bla bla somemore text here


$ cat March-26th.txt

 more text here...


 some more text here...
 Harry


$ cat  April-29th.txt

  Ding Ding Ding

$ cat  June-3rd.txt
   Avada KaDavra

$ cat January-1st.txt
   Happy New Year
...