I don’t know what your problem is (would it be a college exercise?), but if you’re trying to build an agenda or something like that, I would suggest using a more appropriate and easy-to-manipulate storage format.
If it’s something more amateur, using even text file storage,
I would suggest using a JSON, one XML or a YAML. Everyone has
ready packages in Python. If it’s something more professional, maybe it’s
better use a database (Mysql, for example, which also has
ready-made packages in Python).
Anyway, there are several options to do what you want. To make it easy, I suggest using the package datetime
to identify the dates. But for this you need to set the location in Portuguese before and, very important, use the name of the day of the week correctly ("Monday", instead of "Monday").
The following code reads line by line, testing each line to see if it finds a date (uses the function datetime.strptime
, which makes an exception if it is not a valid date - when I consider the content of the date previously recognized, stored in the variable date
). If it is a date, it opens a new "key" in the dictionary info
based on that date. If it is not, it considers as a content of that entry in your agenda, and simply accumulates it in the current key (by doing info[date] += line + '\n'
).
Note that "logic" is essentially:
- Read a line if you haven’t reached the end of the file.
- Checks if it is a date.
- If it is 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. Back to step 1.
You can implement this logic anyway, and the cat jump is precisely in step 2 (check if it is a date). This code only tries to facilitate this identification using the packages locale
and datetime
. But nothing stops you from using regular expressions or even manual comparison.
Here’s 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 entrance has to be (with "Monday****" instead of 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 exit code is this:
>teste
Digite a data para consulta:6 Março 2017- Segunda-feira
aniversario do Salomao
- fazer compras
P.S.: Note that the date format is set as dia Mês ano-
Dia_da_semana
based on the format %d %B %Y- %A
. If you need
change the format (either by 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.
I didn’t understand the issue or the comment in my reply. The code of the TWO answers you have do just that. This "simpler" logic is wrong.
– Luiz Vieira
@Luiz Vieira: Sorry, I wanted to understand the mistake in what I thought to do! The answers are perfect
– Ed S
Well, there are several mistakes. The main thing is that
"6 Março 2017" in f.readlines()
only returns true if the text exists on the list of lines. It doesn’t indicate what line the text is on, so you can’t do anything other than know if it exists.– Luiz Vieira