diff --git a/.gitignore b/.gitignore index 723ef36..ca4cd9c 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -.idea \ No newline at end of file +.idea +apuntes \ No newline at end of file diff --git a/proyecto/__init__.py b/proyecto/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/proyecto/filtrado.py b/proyecto/filtrado.py new file mode 100644 index 0000000..ae30aee --- /dev/null +++ b/proyecto/filtrado.py @@ -0,0 +1,28 @@ +from validacion import * +from normalizacion import * + +def filtrar_telefono(fichero, tel): + f = open(fichero, "r", encoding="utf-8") + for i in f.readlines(): + telefono = i.split(";")[0] + if telefono.strip() == tel: + print(i) + else: + continue + +def filtrar_nif(fichero, nif): + f = open(fichero, "r", encoding="utf-8") + for i in f.readlines(): + n = i.split(";")[1] + if n.strip() == nif: + print(i) + else: + continue + +def filtrar_instante(inicio, fin, fichero): + f = open(fichero, "r", encoding="utf-8") + inicio = normalizar_instante(inicio.strip(), 3) + fin = normalizar_instante(fin.strip(), 3) + for i in f.readlines(): + instante = i.split(";")[2] + # terminar \ No newline at end of file diff --git a/proyecto/main.py b/proyecto/main.py new file mode 100644 index 0000000..11f45a5 --- /dev/null +++ b/proyecto/main.py @@ -0,0 +1,70 @@ +import regex as re +import sys + +from filtrado import * +from validacion import * +from normalizacion import * +from variables import * +# -n: normaliza el fichero en pos[-n] + 1 con los formatos: +# +34[numero] +# formato 2 para instantes temporales +# formato 3 para coordenadas +# nif, producto y precio originales +# se puede pasar f1 para el formato de las fechas y f2 para las coordenadas [param. opc.] + +# -sphone, -snif: filtran por teléfono y nif +# -stime: filtran de una fecha hasta otra +# -slocation: puntos extra + +# la salida aparece como campo1 ; campo2 ; campo3 ; ... +# los errores de formato o sintaxis en los argumentos son exit N +# los errores en el archivo se ignoran + +def main(): + l = open("../log.txt", encoding="utf-8") + for linea in l.readlines(): + pass + # print(validarEntrada(linea.strip())) + + + # n, sphone, stime, snif + arg_prueba = "-sphone 123456789 telefonos -stime 11:11:11 11:11:12 tiempos -n normalizar 1 2 -snif 12345678B fichero" + argumentos = r"(?P-sphone (?P\S*) (?P\S*))|(?P-stime (?P\S*) (?P\S*) (?P\S*))|(?P-n (?P\S*))|(?P-snif (?P\S*) (?P\S*))" + A = re.compile(argumentos) + match = A.finditer(arg_prueba) + + argv = sys.argv + try: + if '-n' in argv: + fichero = argv[argv.index('-n') + 1] + try: # un poco chapucero + formato_fecha = int(argv[argv.index('-n') + 2]) + formato_coordenadas = int(argv[argv.index('-n') + 3]) + except IndexError: + formato_fecha = 2 + formato_coordenadas = 3 + normalizar(fichero, formato_fecha, formato_coordenadas) + + elif '-sphone' in argv: + telefono = int(argv[argv.index('-sphone') + 1]) + fichero = argv[argv.index('-sphone') + 2] + filtrar_telefono(telefono, fichero) + + elif '-snif' in argv: + nif = argv[argv.index('-snif') + 1] + fichero = argv[argv.index('-snif') + 2] + filtrar_nif(nif, fichero) + + elif '-stime' in argv: # convertir entre formatos + desde = argv[argv.index('-stime') + 1] + hasta = argv[argv.index('-stime') + 2] + fichero = argv[argv.index('-stime') + 3] + print("stime") + except FileNotFoundError as e: + print(e) + exit(1) + + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/proyecto/normalizacion.py b/proyecto/normalizacion.py new file mode 100644 index 0000000..56d5a16 --- /dev/null +++ b/proyecto/normalizacion.py @@ -0,0 +1,59 @@ +from validacion import * +from variables import * + +def normalizar_instante(instante, formato): + d = validarInstante(instante) + if d is None: + return None + + if formato == 1: + if not d['mes'].isdigit(): + d['mes'] = meses.index(d['mes'].lower()) + 1 + return f"{d['año']}-{d['mes']:0>2}-{d['dia']:0>2} {d['hora']:0>2}:{d['minuto']}" + + elif formato == 2: + if d['mes'] in meses: + return f"{d['mes']} {d['dia']}, {d['año']} {d['hora']}:{d['minuto']} {d['segundo']}" + else: + if int(d['hora']) > 12: + d['hora'] = int(d['hora']) % 12 + + if d['mes'].isdigit(): + d['mes'] = meses[int(d['mes']) - 1] + + return f"{d['mes'].lower()} {d['dia']}, {d['año']} {d['hora']}:{d['minuto']} AM" + + elif formato == 3: + if not d['mes'].isdigit(): + d['mes'] = meses.index(d['mes'].lower()) + 1 + + if not d['segundo'].isdigit(): + d['segundo'] = '00' + return f"{d['hora']}:{d['minuto']}:{d['segundo']} {d['dia']}/{d['mes']}/{d['año']}" + + +def normalizar_telefono(telefono): + telefono = re.sub(r'( )|(-)', r'', telefono) + if telefono[0] != '+': + return f'+34{telefono}' + return telefono + +def normalizar_coordenada(coordenada, formato): + c = validarCoordenada(coordenada, formato) + return c + +def normalizar(fichero, formato_fecha, formato_coordenadas): + try: + f = open(fichero, 'r') + except: + exit(1) + n = 0 + for i in f.readlines(): + telefono, nif, instante, coordenada, producto, precio = i.split(";") + instante = normalizar_instante(instante.strip(), 1) + telefono = normalizar_telefono(telefono.strip()) + coordenada = normalizar_coordenada(coordenada.strip(), 3) + print(instante, telefono, coordenada) + n += 1 + + print(n) diff --git a/final.py b/proyecto/validacion.py similarity index 51% rename from final.py rename to proyecto/validacion.py index 8812b65..44aedae 100644 --- a/final.py +++ b/proyecto/validacion.py @@ -1,29 +1,6 @@ import regex as re -import sys +from variables import * -# -n: normaliza el fichero en pos[-n] + 1 con los formatos: -# +34[numero] -# formato 2 para instantes temporales -# formato 3 para coordenadas -# nif, producto y precio originales -# se puede pasar f1 para el formato de las fechas y f2 para las coordenadas [param. opc.] - -# -sphone, -snif: filtran por teléfono y nif -# -stime: filtran de una fecha hasta otra -# -slocation: puntos extra - -# la salida aparece como campo1 ; campo2 ; campo3 ; ... -# los errores de formato o sintaxis en los argumentos son exit N -# los errores en el archivo se ignoran - - -letras = ['T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E'] -reemplazo_nie = { - 'X': 0, - 'Y': 1, - 'Z': 2, - None: '', -} def comprobarLetra(dni: str): num = int(dni[:-1]) letra = dni[-1] @@ -32,13 +9,16 @@ def comprobarLetra(dni: str): else: return True -t = r"(?P\d{3})-(?P\d{3})-(?P\d{3})" -T = re.compile(t) -def validarTelefono(telefono): +def validarTelefono(telefono): # revisar sesión 6 ej 1 match = T.match(telefono) if match is not None: + # if match.group('prefijo') is None: + # prefijo = '+34' + # else: + # prefijo = match.group('prefijo') return { + # 'prefijo': prefijo, 'parte1': match.group('parte1'), 'parte2': match.group('parte2'), 'parte3': match.group('parte3'), @@ -46,8 +26,7 @@ def validarTelefono(telefono): return None -d = r"(((?P[X-Z])*(?P\d{7}))|(?P\d{8}))-(?P[A-HJ-NP-TV-Z])" # cambiar, el nie son 7 -D = re.compile(d, flags=re.I|re.M) + def validarDni(dni): match = D.match(dni) @@ -71,28 +50,29 @@ def validarDni(dni): else: return None -i = r"((?P0{3}[1-9]|\d{4})-(?P0\d|1[0-2])-(?P[0-2]\d|3[01])\s+(?P[0-1]\d|2[0-4]):(?P[0-5]\d))|((?Pjanuary|february|march|april|may|june|july|august|september|october|november|december)\s+(?P\d|[12]\d|3[01]),\s+(?P0{3}[1-9]|\d{4})\s+(?P[1-9]|1[0-2]):(?P[0-5]\d)\s+(?P[ap]m))|((?P[01]\d|2[0-3]):(?P[0-5]\d):(?P[0-5]\d)\s+(?P[0-2]\d|3[01])/(?P0\d|1[0-2])/(?P0{3}[1-9]|\d{4}))" -I = re.compile(i, flags=re.IGNORECASE) + def validarInstante(instante): match = I.match(instante) - if match and not match['segundo']: + if match and not match['segundo']: # formato 1 return { - 'anyo': match.group('anyo'), + 'año': match.group('anyo'), 'mes': match.group('mes'), 'dia': match.group('dia'), 'hora': match.group('hora'), 'minuto': match.group('minuto'), + 'segundo': '00' } - elif match and match['segundo']: + elif match and match['segundo']: # formatos 2 y 3 return { - 'anyo': match.group('anyo'), + 'año': match.group('anyo'), 'mes': match.group('mes'), 'dia': match.group('dia'), 'hora': match.group('hora'), 'minuto': match.group('minuto'), 'segundo': match.group('segundo'), } - return None + else: + return None def decimalGrado(numero): @@ -110,11 +90,9 @@ def gradoDecimal(grados,minutos,segundos): return a -def coord(cadena, form=1): - R = r"( *(?P([0-2][0-9][0-9])|(3[0-5][0-9]))(?P[0-6][0-9])(?P[0-6][0-9]\.\d{4})(?P(N|S))(?P([0-2][0-9][0-9])|(3[0-5][0-9]))(?P[0-6][0-9])(?P[0-6][0-9]\.\d{4})(?P(W|E)) *)|( *(?P((1[0-9][0-9])|(2[0-9][0-9])|(3[0-5][0-9])|\d{2}|\d{1}))° *(?P([0-5][0-9])|[0-9])' *(?P(([0-5][0-9])|[0-9])\.\d{4})\" *(?P(N|S)) *, *(?P((1[0-9][0-9])|(2[0-9][0-9])|(3[0-5][0-9])|\d{2}|\d{1}))° *(?P([0-5][0-9])|[0-9])' *(?P(([0-5][0-9])|[0-9])\.\d{4})\" *(?P(W|E)) *)|( *((?P[+|\-| ])(?P(([1-8]?[0-9])\.\d+)|90)) *, *((?P[+|\-| ])(?P([1][1-7][1-9]\.\d+)|([1-8]?[0-9]\.\d+))|90) *)" - P = re.compile( R ) - if P.fullmatch(cadena): - M = P.fullmatch(cadena) +def validarCoordenada(cadena, form): + if P.fullmatch(): + M = P.fullmatch() if M.group("Grados1"): grados1 = M.group("Grados1") grados2 = M.group("Grados2") @@ -175,7 +153,7 @@ def validarEntrada(entrada): tel = validarTelefono(telefono.strip()) dni = validarDni(dni.strip()) fecha = validarInstante(fecha.strip()) - coordenadas = coord(coordenadas.strip()) + coordenadas = validarCoordenada(coordenadas.strip()) valores = { 'telefono': tel, @@ -189,46 +167,3 @@ def validarEntrada(entrada): if valores[k] is None: return None return valores -def main(): - print(validarTelefono("623-121-153")) - print(validarDni("48755850-J")) - print(validarDni("Z9876543-A")) - print(validarInstante("october 12, 1925 1:12 pm")) - l = open("log.txt", encoding="utf-8") - for linea in l.readlines(): - pass - # print(validarEntrada(linea.strip())) - - - # n, sphone, stime, snif - arg_prueba = "-sphone 123456789 telefonos -stime 11:11:11 11:11:12 tiempos -n normalizar -snif 12345678B fichero" - argumentos = r"(?P-sphone (?P\S*) (?P\S*))|(?P-stime (?P\S*) (?P\S*) (?P\S*))|(?P-n (?P\S*))|(?P-snif (?P\S*) (?P\S*))" - A = re.compile(argumentos) - match = A.finditer(arg_prueba) - - argv = sys.argv - try: - if '-n' in argv: - fichero = argv[argv.index('-n') + 1] - formato_fecha = int(argv[argv.index('-n') + 2]) - formato_coordenadas = int(argv[argv.index('-n') + 3]) - print("n") - else: - if '-sphone' in argv: - telefono = int(argv[argv.index('-sphone') + 1]) - fichero = argv[argv.index('-sphone') + 2] - print("sphone") - if '-snif' in argv: - nif = argv[argv.index('-snif') + 1] - fichero = argv[argv.index('-snif') + 2] - if '-stime' in argv: - desde = argv[argv.index('-stime') + 1] - hasta = argv[argv.index('-stime') + 2] - fichero = argv[argv.index('-stime') + 3] - except Exception as e: - print(e) - - - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/proyecto/variables.py b/proyecto/variables.py new file mode 100644 index 0000000..30701c1 --- /dev/null +++ b/proyecto/variables.py @@ -0,0 +1,21 @@ +import regex as re +letras = ['T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E'] +reemplazo_nie = { + 'X': 0, + 'Y': 1, + 'Z': 2, + None: '', +} +meses = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'] + +t = r"(?P\+[0-9]+)? *(?P\d{3})-(?P\d{3})-(?P\d{3})" +T = re.compile(t) + +d = r"(((?P[X-Z])*(?P\d{7}))|(?P\d{8}))-(?P[A-HJ-NP-TV-Z])" # cambiar, el nie son 7 +D = re.compile(d, flags=re.I|re.M) + +i = r"((?P0{3}[1-9]|\d{4})-(?P0\d|1[0-2])-(?P[0-2]\d|3[01])\s+(?P[0-1]\d|2[0-4]):(?P[0-5]\d))|((?Pjanuary|february|march|april|may|june|july|august|september|october|november|december)\s+(?P\d|[12]\d|3[01]),\s+(?P0{3}[1-9]|\d{4})\s+(?P[1-9]|1[0-2]):(?P[0-5]\d)\s+(?P[ap]m))|((?P[01]\d|2[0-3]):(?P[0-5]\d):(?P[0-5]\d)\s+(?P[0-2]\d|3[01])/(?P0\d|1[0-2])/(?P0{3}[1-9]|\d{4}))" +I = re.compile(i, flags=re.IGNORECASE) + +R = r"( *(?P([0-2][0-9][0-9])|(3[0-5][0-9]))(?P[0-6][0-9])(?P[0-6][0-9]\.\d{4})(?P(N|S))(?P([0-2][0-9][0-9])|(3[0-5][0-9]))(?P[0-6][0-9])(?P[0-6][0-9]\.\d{4})(?P(W|E)) *)|( *(?P((1[0-9][0-9])|(2[0-9][0-9])|(3[0-5][0-9])|\d{2}|\d{1}))° *(?P([0-5][0-9])|[0-9])' *(?P(([0-5][0-9])|[0-9])\.\d{4})\" *(?P(N|S)) *, *(?P((1[0-9][0-9])|(2[0-9][0-9])|(3[0-5][0-9])|\d{2}|\d{1}))° *(?P([0-5][0-9])|[0-9])' *(?P(([0-5][0-9])|[0-9])\.\d{4})\" *(?P(W|E)) *)|( *((?P[+|\-| ])(?P(([1-8]?[0-9])\.\d+)|90)) *, *((?P[+|\-| ])(?P([1][1-7][1-9]\.\d+)|([1-8]?[0-9]\.\d+))|90) *)" +P = re.compile(R) diff --git a/sesion6.py b/sesion6.py new file mode 100644 index 0000000..85bd44d --- /dev/null +++ b/sesion6.py @@ -0,0 +1,151 @@ +import regex as re +import sys + +# -n: normaliza el fichero en pos[-n] + 1 con los formatos: +# +34[numero] +# formato 2 para instantes temporales +# formato 3 para coordenadas +# nif, producto y precio originales +# se puede pasar f1 para el formato de las fechas y f2 para las coordenadas [param. opc.] + +# -sphone, -snif: filtran por teléfono y nif +# -stime: filtran de una fecha hasta otra +# -slocation: puntos extra + +# la salida aparece como campo1 ; campo2 ; campo3 ; ... +# los errores de formato o sintaxis en los argumentos son exit N +# los errores en el archivo se ignoran + + +letras = ['T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E'] +reemplazo_nie = { + 'X': 0, + 'Y': 1, + 'Z': 2, + None: '', +} +def comprobarLetra(dni: str): + num = int(dni[:-1]) + letra = dni[-1] + if letras[num % 23] != letra: + return False + else: + return True + +t = r"(?P\d{3})-(?P\d{3})-(?P\d{3})" +T = re.compile(t) + +def validarTelefono(telefono): + match = T.match(telefono) + if match is not None: + return { + 'parte1': match.group('parte1'), + 'parte2': match.group('parte2'), + 'parte3': match.group('parte3'), + } + + return None + +d = r"(((?P[X-Z])*(?P\d{7}))|(?P\d{8}))-(?P[A-HJ-NP-TV-Z])" # cambiar, el nie son 7 +D = re.compile(d, flags=re.I|re.M) + +def validarDni(dni): + match = D.match(dni) + if match and match['letrainicio']: + valido = comprobarLetra(f"{reemplazo_nie[match['letrainicio']]}{match["numero"]}{match["letrafinal"]}") + return { + 'letrainicio': match.group('letrainicio'), + 'numero': match.group('numero'), + 'letrafinal': match.group('letrafinal'), + } + elif match and not match['letrainicio']: + valido = comprobarLetra(f"{match["numero"]}{match["letrafinal"]}") + return { + 'numero': match['numero'], + 'letrafinal': match.group('letrafinal'), + } + else: + return None + +i = r"((?P0{3}[1-9]|\d{4})-(?P0\d|1[0-2])-(?P[0-2]\d|3[01])\s+(?P[0-1]\d|2[0-4]):(?P[0-5]\d))|((?Pjanuary|february|march|april|may|june|july|august|september|october|november|december)\s+(?P\d|[12]\d|3[01]),\s+(?P0{3}[1-9]|\d{4})\s+(?P[1-9]|1[0-2]):(?P[0-5]\d)\s+(?P[ap]m))|((?P[01]\d|2[0-3]):(?P[0-5]\d):(?P[0-5]\d)\s+(?P[0-2]\d|3[01])/(?P0\d|1[0-2])/(?P0{3}[1-9]|\d{4}))" +I = re.compile(i, flags=re.IGNORECASE) +def validarInstante(instante): + match = I.match(instante) + if match and not match['segundo']: + return { + 'anyo': match.group('anyo'), + 'mes': match.group('mes'), + 'dia': match.group('dia'), + 'hora': match.group('hora'), + 'minuto': match.group('minuto'), + } + elif match and match['segundo']: + return { + 'anyo': match.group('anyo'), + 'mes': match.group('mes'), + 'dia': match.group('dia'), + 'hora': match.group('hora'), + 'minuto': match.group('minuto'), + 'segundo': match.group('segundo'), + } + return None + +def validarEntrada(entrada): + telefono, dni, fecha, coordenadas, producto, coste = entrada.split(";") + tel = validarTelefono(telefono.strip()) + dni = validarDni(dni.strip()) + fecha = validarInstante(fecha.strip()) + + valores = { + 'telefono': tel, + 'dni': dni, + 'fecha': fecha, + 'coordenadas': coordenadas, + 'producto': producto, + 'coste': coste, + } + for k in valores.keys(): + if valores[k] is None: + return None + return valores + +def coord(): + R = r"( *(?P([0-2][0-9][0-9])|(3[0-5][0-9]))(?P[0-6][0-9])gi(?P[0-6][0-9]\.\d{4})(?P[N|S])(?P([0-2][0-9][0-9])|(3[0-5][0-9]))(?P[0-6][0-9])(?P[0-6][0-9]\.\d{4})(?P[W|E]) *)|( *(?P((1[0-9][0-9])|(2[0-9][0-9])|(3[0-5][0-9])|\d{2}|\d{1}))° *(?P([0-5][0-9])|[0-9])' *(?P(([0-5][0-9])|[0-9])\.\d{4})\" *(?P(N|S)) *, *(?P((1[0-9][0-9])|(2[0-9][0-9])|(3[0-5][0-9])|\d{2}|\d{1}))° *(?P([0-5][0-9])|[0-9])' *(?P(([0-5][0-9])|[0-9])\.\d{4})\" *(?P(N|S)) *)|( *(?P[(+|\-| ](([1-8]?[0-9]\.\d+)|90)) *, *(?P[(+|\-| ](([1-8]?[0-9]\.\d+)|90)) *)" + P = re.compile( R ) + cadena = " 74°28' 5.0000\" S , 46°4' 12.0000\"E " + if P.fullmatch(cadena): + M = P.fullmatch(cadena) + #f1 print(f'{M.group("Coord1")}, {M.group("Coord2")}') + #f2 print(f'{M.group("Grados1")}º {M.group("Minutos1")}\' {M.group("Segundos1")}" {M.group("Letra1")}, {M.group("Grados2")}º {M.group("Minutos2")}\' {M.group("Segundos2")}" {M.group("Letra2")}') + #f3 print(f'{M.group("Grados1"):0>3}{M.group("Minutos1"):0>2}{M.group("Segundos1"):0>7}{M.group("Letra1")}{M.group("Grados2"):0>3}{M.group("Minutos2"):0>2}{M.group("Segundos2"):0>7}{M.group("Letra2")}') + else: + print("No valido") + ''' + if P.fullmatch(cadena): + M = P.fullmatch(cadena) + print("Primera Coordenada: Grados: ",M.group("Grados1"), " minutos: ", M.group("Minutos1")," Segundos: ",M.group("Segundos1"), " letra: ", M.group("Letra1")) + print("Segunda Coordenada: Grados: ",M.group("Grados2"), " minutos: ", M.group("Minutos2")," Segundos: ",M.group("Segundos2"), " letra: ", M.group("Letra2")) + else: + print("No valido") + ''' +def main(): + print(validarTelefono("623-121-153")) + print(validarDni("48755850-J")) + print(validarDni("Z9876543-A")) + print(validarInstante("october 12, 1925 1:12 pm")) + coord() + l = open("log.txt", encoding="utf-8") + for linea in l.readlines(): + print(validarEntrada(linea.strip())) + + argv = ' '.join([a for a in sys.argv[1:]]) + # n, sphone, stime, snif + arg_prueba = "-snif 12345678B fichero -sphone 123456789 telefonos -n normalizar -stime 11:11:11 11:11:12 tiempos" + argumentos = r'(?P-sphone (?P\S*) (?P\S*))|(?P-stime (?P\S*) (?P\S*) (?P\S*))|(?Pn (?P\S*))|(?P-snif (?P\S*) (?P\S*))' + A = re.compile(argumentos) + match = A.match(arg_prueba) + print(type(match)) + + +if __name__ == "__main__": + main() \ No newline at end of file