I do not know what your problem is all about (would it be a college exercise?), but if you're trying to build an agenda or something, I'd suggest using a more appropriate and easy-to-handle storage format. / p>
If it's something more amateur, using same text file storage,
I would suggest using a JSON , an XML or a YAML . Everyone has
packages in Python. If it's something more professional, maybe it's
best to use a database ( MySQL , for example, which also has
packages ready in Python).
In any case, there are several options to do what you want. To facilitate, I suggest using the datetime
package to identify the dates. But for this you need to set the location in Portuguese before and, very importantly, use the name of the day of the week correctly ("Monday" instead of "Monday"). p>
The following code reads line by line, testing each line to see if it finds a date (it uses the datetime.strptime
function, which throws an exception if it is not a valid date - when I consider it as content from the previously recognized date , stored in the date
variable). If it's a date, it opens a new "key" in the info
dictionary based on that date. If it is not, it considers it as a content of that entry in your calendar, and simply accumulates it in the current key (when doing info[date] += line + '\n'
).
Note that "logic" is essentially:
Read a line if it has not yet reached the end of the file.
Checks if it's a date.
If it's a date, open a new "record" for it, and go back to step 1.
If it is not a date, add the line as content in the current record. Go back to step 1.
You can implement this logic anyway, and the cat's jump is just in step 2 (check if it's a date). This code only tries to facilitate this identification using the locale
and datetime
packages. But nothing prevents you from using regular expressions or even manual comparison.
Here is the code:
import sys
import locale
from datetime import datetime
# Define a localização para Português do Brasil
locale.setlocale(locale.LC_ALL, 'ptg_bra') # No Windows!
# Em outro OS provavelmente será:
# locale.setlocale(locale.LC_ALL, 'pt_BR')
date = ''
info = {}
with open('teste.txt', 'r') as f:
for line in f.readlines():
line = line.strip('\n ') # Remove quebras de linhas e espaços
# Tenta converter a linha atual para uma data (no formato esperado!)
# Se sucesso, abre uma nova "chave" de conteúdo
try:
key = datetime.strptime(line, '%d %B %Y- %A')
date = key
info[date] = ''
# Se falhou, o conteúdo pertence à chave atual (se há uma)
except ValueError:
if date != '':
info[date] += line + '\n'
date = input('Digite a data para consulta:')
try:
date = datetime.strptime(date, '%d %B %Y- %A')
except ValueError:
print('O valor [{}] não é uma data válida.'.format(date))
sys.exit(-1)
print(info[date])
Remembering that the entry has to be (with "Monday ** - fair **" rather than just "Monday"):
4 Março 2017- Sábado
meu aniversario
-prova de calculo
6 Março 2017- Segunda-feira
aniversario do Salomao
- fazer compras
[. . .]
The output of the code is this:
>teste
Digite a data para consulta:6 Março 2017- Segunda-feira
aniversario do Salomao
- fazer compras
Q.: Note that the date format is set to dia Mês ano-
Dia_da_semana
based on %d %B %Y- %A
format. If you need
change the format (even adding or removing a space!),
you need to change the format! The list of formats can be consulted
in the documentation or in this quick guide .