Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f5ce288871 | ||
|
|
77fef039e0 | ||
|
|
1defdd5e6c | ||
|
|
f3b588a3b9 | ||
|
|
ead080b2e5 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1 +1,2 @@
|
|||||||
.idea
|
.idea
|
||||||
|
apuntes
|
||||||
234
final.py
234
final.py
@@ -1,234 +0,0 @@
|
|||||||
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<parte1>\d{3})-(?P<parte2>\d{3})-(?P<parte3>\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<letrainicio>[X-Z])*(?P<numero>\d{7}))|(?P<numero>\d{8}))-(?P<letrafinal>[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']}")
|
|
||||||
if valido:
|
|
||||||
return {
|
|
||||||
'letrainicio': match.group('letrainicio'),
|
|
||||||
'numero': match.group('numero'),
|
|
||||||
'letrafinal': match.group('letrafinal'),
|
|
||||||
}
|
|
||||||
return None
|
|
||||||
elif match and not match['letrainicio']:
|
|
||||||
valido = comprobarLetra(f"{match['numero']}{match['letrafinal']}")
|
|
||||||
if valido:
|
|
||||||
return {
|
|
||||||
'numero': match['numero'],
|
|
||||||
'letrafinal': match.group('letrafinal'),
|
|
||||||
}
|
|
||||||
return None
|
|
||||||
else:
|
|
||||||
return None
|
|
||||||
|
|
||||||
i = r"((?P<anyo>0{3}[1-9]|\d{4})-(?P<mes>0\d|1[0-2])-(?P<dia>[0-2]\d|3[01])\s+(?P<hora>[0-1]\d|2[0-4]):(?P<minuto>[0-5]\d))|((?P<mes>january|february|march|april|may|june|july|august|september|october|november|december)\s+(?P<dia>\d|[12]\d|3[01]),\s+(?P<anyo>0{3}[1-9]|\d{4})\s+(?P<hora>[1-9]|1[0-2]):(?P<minuto>[0-5]\d)\s+(?P<segundo>[ap]m))|((?P<hora>[01]\d|2[0-3]):(?P<minuto>[0-5]\d):(?P<segundo>[0-5]\d)\s+(?P<dia>[0-2]\d|3[01])/(?P<mes>0\d|1[0-2])/(?P<anyo>0{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 decimalGrado(numero):
|
|
||||||
a = float(numero)
|
|
||||||
grados = int(numero)
|
|
||||||
b = a - grados
|
|
||||||
minutos = int(b*60)
|
|
||||||
c = b*60-minutos
|
|
||||||
segundos = int(c*60)
|
|
||||||
return grados,minutos,segundos
|
|
||||||
|
|
||||||
|
|
||||||
def gradoDecimal(grados,minutos,segundos):
|
|
||||||
a = float(segundos)/3600 + float(minutos)/60 + float(grados)
|
|
||||||
return a
|
|
||||||
|
|
||||||
|
|
||||||
def coord(cadena, form=1):
|
|
||||||
R = r"( *(?P<Grados1>([0-2][0-9][0-9])|(3[0-5][0-9]))(?P<Minutos1>[0-6][0-9])(?P<Segundos1>[0-6][0-9]\.\d{4})(?P<Letra1>(N|S))(?P<Grados2>([0-2][0-9][0-9])|(3[0-5][0-9]))(?P<Minutos2>[0-6][0-9])(?P<Segundos2>[0-6][0-9]\.\d{4})(?P<Letra2>(W|E)) *)|( *(?P<Grados1>((1[0-9][0-9])|(2[0-9][0-9])|(3[0-5][0-9])|\d{2}|\d{1}))° *(?P<Minutos1>([0-5][0-9])|[0-9])' *(?P<Segundos1>(([0-5][0-9])|[0-9])\.\d{4})\" *(?P<Letra1>(N|S)) *, *(?P<Grados2>((1[0-9][0-9])|(2[0-9][0-9])|(3[0-5][0-9])|\d{2}|\d{1}))° *(?P<Minutos2>([0-5][0-9])|[0-9])' *(?P<Segundos2>(([0-5][0-9])|[0-9])\.\d{4})\" *(?P<Letra2>(W|E)) *)|( *((?P<Signo1>[+|\-| ])(?P<Coord1>(([1-8]?[0-9])\.\d+)|90)) *, *((?P<Signo2>[+|\-| ])(?P<Coord2>([1][1-7][1-9]\.\d+)|([1-8]?[0-9]\.\d+))|90) *)"
|
|
||||||
P = re.compile( R )
|
|
||||||
if P.fullmatch(cadena):
|
|
||||||
M = P.fullmatch(cadena)
|
|
||||||
if M.group("Grados1"):
|
|
||||||
grados1 = M.group("Grados1")
|
|
||||||
grados2 = M.group("Grados2")
|
|
||||||
minutos1 = M.group("Minutos1")
|
|
||||||
minutos2 = M.group("Minutos2")
|
|
||||||
segundos1 = M.group("Segundos1")
|
|
||||||
segundos2 = M.group("Segundos2")
|
|
||||||
letra1 = M.group("Letra1")
|
|
||||||
letra2 = M.group("Letra2")
|
|
||||||
num1 = gradoDecimal(grados1,minutos1,segundos1)
|
|
||||||
num2 = gradoDecimal(grados2,minutos2,segundos2)
|
|
||||||
if letra1 == 'N':
|
|
||||||
simb1 = '+'
|
|
||||||
else:
|
|
||||||
simb1 = '-'
|
|
||||||
if letra2== 'E':
|
|
||||||
simb2 = '+'
|
|
||||||
else:
|
|
||||||
simb2 = '-'
|
|
||||||
else:
|
|
||||||
num1 = float(M.group("Coord1"))
|
|
||||||
num2 = float(M.group("Coord2"))
|
|
||||||
simb1 = M.group("Signo1")
|
|
||||||
simb2 = M.group("Signo2")
|
|
||||||
|
|
||||||
if form == 1:
|
|
||||||
return f'{simb1}{round(num1,4)}, {simb2}{round(num2,4)}'
|
|
||||||
elif form == 2:
|
|
||||||
grados1, minutos1, segundos1= decimalGrado(num1)
|
|
||||||
grados2, minutos2, segundos2 = decimalGrado(num2)
|
|
||||||
if simb1 == '+':
|
|
||||||
letra1 = 'N'
|
|
||||||
else:
|
|
||||||
letra1 = 'S'
|
|
||||||
if simb2 == '+':
|
|
||||||
letra2 = 'E'
|
|
||||||
else:
|
|
||||||
letra2 = 'W'
|
|
||||||
return f'{grados1}º {minutos1}\' {segundos1:}.0000" {letra1}, {grados2}º {minutos2}\' {segundos2}.0000" {letra2}'
|
|
||||||
elif form == 3:
|
|
||||||
grados1, minutos1, segundos1 = decimalGrado(num1)
|
|
||||||
grados2, minutos2, segundos2 = decimalGrado(num2)
|
|
||||||
if simb1 == '+':
|
|
||||||
letra1 = 'N'
|
|
||||||
else:
|
|
||||||
letra1 = 'S'
|
|
||||||
if simb2 == '+':
|
|
||||||
letra2 = 'E'
|
|
||||||
else:
|
|
||||||
letra2 = 'W'
|
|
||||||
return f'{grados1:0>3}{minutos1:0>2}{segundos1:0>2}.0000{letra1}{grados2:0>3}{minutos2:0>2}{segundos2:0>2}.0000{letra2}'
|
|
||||||
|
|
||||||
else:
|
|
||||||
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())
|
|
||||||
coordenadas = coord(coordenadas.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 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>-sphone (?P<telefono>\S*) (?P<fichero>\S*))|(?P<stime>-stime (?P<inicio>\S*) (?P<final>\S*) (?P<fichero1>\S*))|(?P<n>-n (?P<fichero2>\S*))|(?P<snif>-snif (?P<nif>\S*) (?P<fichero3>\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()
|
|
||||||
0
proyecto/__init__.py
Normal file
0
proyecto/__init__.py
Normal file
56
proyecto/filtrado.py
Normal file
56
proyecto/filtrado.py
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
from normalizacion import *
|
||||||
|
from validacion import validarCoordenada
|
||||||
|
from util import haversine, convertirSegundos
|
||||||
|
|
||||||
|
def filtrar_telefono(fichero, tel):
|
||||||
|
f = open(fichero, "r", encoding="utf-8")
|
||||||
|
tel_n = normalizarTelefono(tel)
|
||||||
|
for linea in f.readlines():
|
||||||
|
telefono = normalizarTelefono(linea.split(";")[0])
|
||||||
|
if telefono.strip() == tel_n:
|
||||||
|
print(linea, end='')
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
|
||||||
|
def filtrar_nif(fichero, nif):
|
||||||
|
f = open(fichero, "r", encoding="utf-8")
|
||||||
|
if D.match(nif) is None:
|
||||||
|
exit(2)
|
||||||
|
|
||||||
|
for linea in f.readlines():
|
||||||
|
n = linea.split(";")[1]
|
||||||
|
if n.strip() == nif:
|
||||||
|
print(linea, end='')
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
|
||||||
|
def filtrar_instante(inicio, fin, fichero):
|
||||||
|
f = open(fichero, "r", encoding="utf-8")
|
||||||
|
inicio = convertirSegundos(validarInstante(inicio))
|
||||||
|
fin = convertirSegundos(validarInstante(fin))
|
||||||
|
|
||||||
|
|
||||||
|
tupla_inicio = tuple([int(inicio[k]) for k in inicio.keys()])
|
||||||
|
tupla_fin = tuple([int(fin[k]) for k in fin.keys()])
|
||||||
|
|
||||||
|
for linea in f.readlines():
|
||||||
|
instante = linea.split(';')[2].strip()
|
||||||
|
if validarCoordenada(linea.split(';')[3].strip()) is None:
|
||||||
|
continue
|
||||||
|
instante = convertirSegundos(validarInstante(instante))
|
||||||
|
tupla_instante = tuple([int(instante[k]) for k in instante.keys()])
|
||||||
|
if tupla_inicio < tupla_instante < tupla_fin:
|
||||||
|
print(linea, end = '')
|
||||||
|
|
||||||
|
def filtrar_distancia(inicio, hasta, fichero):
|
||||||
|
inicio = validarCoordenada(inicio)
|
||||||
|
|
||||||
|
f = open(fichero, 'r', encoding="utf-8")
|
||||||
|
for linea in f.readlines():
|
||||||
|
coordenada = linea.split(';')[3].strip()
|
||||||
|
coordenada = validarCoordenada(coordenada)
|
||||||
|
if coordenada is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if haversine(inicio, coordenada) < float(hasta) * 1000:
|
||||||
|
print(linea, end='')
|
||||||
48
proyecto/main.py
Normal file
48
proyecto/main.py
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import sys
|
||||||
|
|
||||||
|
from filtrado import *
|
||||||
|
from normalizacion import *
|
||||||
|
|
||||||
|
def main():
|
||||||
|
argv = sys.argv
|
||||||
|
try:
|
||||||
|
if '-n' in argv:
|
||||||
|
fichero = argv[argv.index('-n') + 1]
|
||||||
|
try:
|
||||||
|
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 = argv[argv.index('-sphone') + 1]
|
||||||
|
fichero = argv[argv.index('-sphone') + 2]
|
||||||
|
filtrar_telefono(fichero, telefono)
|
||||||
|
|
||||||
|
elif '-snif' in argv:
|
||||||
|
nif = argv[argv.index('-snif') + 1]
|
||||||
|
fichero = argv[argv.index('-snif') + 2]
|
||||||
|
filtrar_nif(fichero, nif)
|
||||||
|
|
||||||
|
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]
|
||||||
|
filtrar_instante(desde, hasta, fichero)
|
||||||
|
|
||||||
|
elif '-slocation' in argv:
|
||||||
|
desde = argv[argv.index('-slocation') + 1]
|
||||||
|
hasta = argv[argv.index('-slocation') + 2]
|
||||||
|
fichero = argv[argv.index('-slocation') + 3]
|
||||||
|
filtrar_distancia(desde, hasta, fichero)
|
||||||
|
|
||||||
|
else:
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
except:
|
||||||
|
exit(2)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
104
proyecto/normalizacion.py
Normal file
104
proyecto/normalizacion.py
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
from validacion import validarCoordenada, validarInstante, validarTelefono
|
||||||
|
from variables import *
|
||||||
|
from util import decimalGrado, convertirSegundos
|
||||||
|
|
||||||
|
|
||||||
|
def normalizarInstante(instante, formato):
|
||||||
|
d = validarInstante(instante)
|
||||||
|
if d is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if formato == 1:
|
||||||
|
d = convertirSegundos(d)
|
||||||
|
|
||||||
|
return f"{d['año']}-{d['mes']:0>2}-{d['dia']:0>2} {d['hora']:0>2}:{d['minuto']}"
|
||||||
|
|
||||||
|
elif formato == 2:
|
||||||
|
try:
|
||||||
|
d['mes'] = meses[int(d['mes']) - 1]
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if int(d['hora']) >= 12:
|
||||||
|
d['hora'] = int(d['hora']) % 12
|
||||||
|
if d['hora'] == 0:
|
||||||
|
d['hora'] = 12
|
||||||
|
|
||||||
|
return f"{d['mes'].lower()} {d['dia']}, {d['año']} {d['hora']}:{d['minuto']} PM"
|
||||||
|
|
||||||
|
if int(d['hora']) == 0:
|
||||||
|
d['hora'] = 12
|
||||||
|
|
||||||
|
return f"{d['mes'].lower()} {d['dia']}, {d['año']} {d['hora']}:{d['minuto']} AM"
|
||||||
|
|
||||||
|
elif formato == 3:
|
||||||
|
d = convertirSegundos(d)
|
||||||
|
return f"{d['hora']:0>2}:{d['minuto']}:{d['segundo']:0>2} {d['dia']:0>2}/{d['mes']:0>2}/{d['año']}"
|
||||||
|
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def normalizarTelefono(telefono):
|
||||||
|
telf = validarTelefono(telefono)
|
||||||
|
if telf is None:
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
if 'num' in telf:
|
||||||
|
num = re.sub(r'( )|(-)', r'', telf['num'])
|
||||||
|
return f'+{num}'
|
||||||
|
elif 'parte1' in telf:
|
||||||
|
telf = re.sub(r'( )|(-)', r'', telefono)
|
||||||
|
if telf[0] != '+':
|
||||||
|
return f'+34{telf}'
|
||||||
|
return telf
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def normalizarCoordenada(coordenada, formato):
|
||||||
|
coordenada = validarCoordenada(coordenada)
|
||||||
|
if coordenada is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if formato == 1:
|
||||||
|
return f"{coordenada['latitud']}, {coordenada['longitud']}"
|
||||||
|
|
||||||
|
elif formato == 2 or formato == 3:
|
||||||
|
letraLatitud = 'N'
|
||||||
|
letraLongitud = 'E'
|
||||||
|
if coordenada['latitud'] < 0:
|
||||||
|
coordenada['latitud'] *= -1
|
||||||
|
letraLatitud = 'S'
|
||||||
|
|
||||||
|
if coordenada['longitud'] < 0:
|
||||||
|
coordenada['longitud'] *= -1
|
||||||
|
letraLongitud = 'W'
|
||||||
|
|
||||||
|
gradosLatitud, minutosLatitud, segundosLatitud = decimalGrado(coordenada['latitud'])
|
||||||
|
gradosLongitud, minutosLongitud, segundosLongitud = decimalGrado(coordenada['longitud'])
|
||||||
|
|
||||||
|
if formato == 2:
|
||||||
|
return f'{gradosLatitud}º {minutosLatitud}\' {segundosLatitud:}.0000" {letraLatitud}, {gradosLongitud}º {minutosLongitud}\' {segundosLongitud}.0000" {letraLongitud}'
|
||||||
|
|
||||||
|
else:
|
||||||
|
return f'{gradosLatitud:0>3}{minutosLatitud:0>2}{segundosLatitud:0>2}.0000{letraLatitud}{gradosLongitud:0>3}{minutosLongitud:0>2}{segundosLongitud:0>2}.0000{letraLongitud}'
|
||||||
|
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def normalizar(fichero, formato_fecha, formato_coordenadas):
|
||||||
|
try:
|
||||||
|
f = open(fichero, 'r', encoding='utf-8')
|
||||||
|
except:
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
for linea in f.readlines():
|
||||||
|
telefono, nif, instante, coordenada, producto, precio = linea.split(";")
|
||||||
|
instante = normalizarInstante(instante.strip(), formato_fecha)
|
||||||
|
telefono = normalizarTelefono(telefono.strip())
|
||||||
|
coordenada = normalizarCoordenada(coordenada.strip(), formato_coordenadas)
|
||||||
|
if coordenada is None:
|
||||||
|
continue
|
||||||
|
print(f"{telefono} ; {nif} ; {instante} ; {coordenada} ; {producto} ; {precio}", end='')
|
||||||
83
proyecto/util.py
Normal file
83
proyecto/util.py
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
from variables import letras, meses
|
||||||
|
import math
|
||||||
|
|
||||||
|
def signoLetra(signo1, signo2):
|
||||||
|
if signo1 == '+':
|
||||||
|
letra1 = 'N'
|
||||||
|
else:
|
||||||
|
letra1 = 'S'
|
||||||
|
|
||||||
|
if signo2 == '+':
|
||||||
|
letra2 = 'E'
|
||||||
|
else:
|
||||||
|
letra2 = 'W'
|
||||||
|
|
||||||
|
return letra1, letra2
|
||||||
|
|
||||||
|
def letraSigno(letra):
|
||||||
|
if letra == 'N' or letra == 'E':
|
||||||
|
signo = '+'
|
||||||
|
elif letra == 'S' or letra == 'W':
|
||||||
|
signo = '-'
|
||||||
|
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
|
||||||
|
return signo
|
||||||
|
|
||||||
|
def decimalGrado(numero):
|
||||||
|
a = float(numero)
|
||||||
|
grados = int(numero)
|
||||||
|
b = a - grados
|
||||||
|
minutos = int(b*60)
|
||||||
|
c = b*60-minutos
|
||||||
|
segundos = int(c*60)
|
||||||
|
return grados,minutos,segundos
|
||||||
|
|
||||||
|
|
||||||
|
def gradoDecimal(grados,minutos,segundos):
|
||||||
|
a = float(segundos)/3600 + float(minutos)/60 + float(grados)
|
||||||
|
return a
|
||||||
|
|
||||||
|
def comprobarLetra(dni: str):
|
||||||
|
num = int(dni[:-1])
|
||||||
|
letra = dni[-1]
|
||||||
|
if letras[num % 23] != letra:
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
return True
|
||||||
|
|
||||||
|
def convertirMes(mes):
|
||||||
|
return meses.index(mes)
|
||||||
|
|
||||||
|
def haversine(coord1, coord2):
|
||||||
|
r = 6367.45 * 1000 # conversión a metros
|
||||||
|
for i in coord1.keys():
|
||||||
|
coord1[i] = math.radians(coord1[i])
|
||||||
|
coord2[i] = math.radians(coord2[i])
|
||||||
|
|
||||||
|
dlat = coord2['latitud'] - coord1['latitud']
|
||||||
|
dlong = coord2['longitud'] - coord1['longitud']
|
||||||
|
h = math.sin(dlat / 2)**2 + math.cos(coord1['latitud']) * math.cos(coord2['latitud']) * math.sin(dlong / 2)**2
|
||||||
|
d = 2 * math.atan2(math.sqrt(h), math.sqrt(1 - h))
|
||||||
|
return d * r
|
||||||
|
|
||||||
|
def convertirSegundos(instante):
|
||||||
|
try:
|
||||||
|
int(instante['mes'])
|
||||||
|
except ValueError:
|
||||||
|
instante['mes'] = convertirMes(instante['mes'].lower())
|
||||||
|
|
||||||
|
try:
|
||||||
|
int(instante['segundo'])
|
||||||
|
|
||||||
|
except ValueError:
|
||||||
|
if instante['segundo'].lower == "pm":
|
||||||
|
instante['hora'] += 12
|
||||||
|
|
||||||
|
if instante['hora'] == 24:
|
||||||
|
instante['hora'] = 0
|
||||||
|
|
||||||
|
instante['segundo'] = 0
|
||||||
|
|
||||||
|
return instante
|
||||||
106
proyecto/validacion.py
Normal file
106
proyecto/validacion.py
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
from variables import *
|
||||||
|
from util import comprobarLetra, gradoDecimal, letraSigno
|
||||||
|
|
||||||
|
|
||||||
|
def validarTelefono(telefono):
|
||||||
|
match = T.match(telefono)
|
||||||
|
if match is not None and not match['num']:
|
||||||
|
return {
|
||||||
|
'parte1': match.group('parte1'),
|
||||||
|
'parte2': match.group('parte2'),
|
||||||
|
'parte3': match.group('parte3'),
|
||||||
|
}
|
||||||
|
elif match is not None and match['num']:
|
||||||
|
return {
|
||||||
|
'num': match.group('num'),
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def validarDni(dni):
|
||||||
|
match = D.match(dni)
|
||||||
|
if match and match['letrainicio']:
|
||||||
|
valido = comprobarLetra(f"{reemplazo_nie[match['letrainicio']]}{match['numero']}{match['letrafinal']}")
|
||||||
|
if valido:
|
||||||
|
return {
|
||||||
|
'letrainicio': match.group('letrainicio'),
|
||||||
|
'numero': match.group('numero'),
|
||||||
|
'letrafinal': match.group('letrafinal'),
|
||||||
|
}
|
||||||
|
return None
|
||||||
|
elif match and not match['letrainicio']:
|
||||||
|
valido = comprobarLetra(f"{match['numero']}{match['letrafinal']}")
|
||||||
|
if valido:
|
||||||
|
return {
|
||||||
|
'numero': match['numero'],
|
||||||
|
'letrafinal': match.group('letrafinal'),
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def validarInstante(instante):
|
||||||
|
match = I.match(instante)
|
||||||
|
if match and not match['segundo']: # formato 1
|
||||||
|
return {
|
||||||
|
'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']: # formatos 2 y 3
|
||||||
|
return {
|
||||||
|
'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'),
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def validarCoordenada(cadena):
|
||||||
|
m = P.fullmatch(cadena)
|
||||||
|
if m is not None:
|
||||||
|
if m.group("Grados1"):
|
||||||
|
grados1 = m.group("Grados1")
|
||||||
|
grados2 = m.group("Grados2")
|
||||||
|
minutos1 = m.group("Minutos1")
|
||||||
|
minutos2 = m.group("Minutos2")
|
||||||
|
segundos1 = m.group("Segundos1")
|
||||||
|
segundos2 = m.group("Segundos2")
|
||||||
|
letra1 = m.group("Letra1")
|
||||||
|
letra2 = m.group("Letra2")
|
||||||
|
|
||||||
|
latitud = gradoDecimal(grados1,minutos1,segundos1)
|
||||||
|
longitud = gradoDecimal(grados2,minutos2,segundos2)
|
||||||
|
signo1 = letraSigno(letra1)
|
||||||
|
signo2 = letraSigno(letra2)
|
||||||
|
|
||||||
|
|
||||||
|
else: # formato 1
|
||||||
|
signo1 = m.group("Signo1")
|
||||||
|
latitud = float(m.group("Coord1"))
|
||||||
|
signo2 = m.group("Signo2")
|
||||||
|
longitud = float(m.group("Coord2"))
|
||||||
|
|
||||||
|
if signo1 == '-':
|
||||||
|
latitud *= -1
|
||||||
|
|
||||||
|
if signo2 == '-':
|
||||||
|
longitud *= -1
|
||||||
|
|
||||||
|
return {
|
||||||
|
'latitud': latitud,
|
||||||
|
'longitud': longitud
|
||||||
|
}
|
||||||
|
|
||||||
|
else:
|
||||||
|
return None
|
||||||
21
proyecto/variables.py
Normal file
21
proyecto/variables.py
Normal file
@@ -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<prefijo>\+[0-9]+)? *(?P<parte1>\d{3})-(?P<parte2>\d{3})-(?P<parte3>\d{3}))|((?P<parte1>\d{3}) *(?P<parte2>\d{3}) *(?P<parte3>\d{3}))|( *\+(?P<num>(\d *){10,15}))"
|
||||||
|
T = re.compile(t)
|
||||||
|
|
||||||
|
d = r"(((?P<letrainicio>[X-Z])*(?P<numero>\d{7}))|(?P<numero>\d{8}))-(?P<letrafinal>[A-HJ-NP-TV-Z])" # cambiar, el nie son 7
|
||||||
|
D = re.compile(d, flags=re.I|re.M)
|
||||||
|
|
||||||
|
i = r"((?P<anyo>0{3}[1-9]|\d{4})-(?P<mes>0\d|1[0-2])-(?P<dia>[0-2]\d|3[01])\s+(?P<hora>[0-1]\d|2[0-4]):(?P<minuto>[0-5]\d))|((?P<mes>january|february|march|april|may|june|july|august|september|october|november|december)\s+(?P<dia>\d|[12]\d|3[01]),\s+(?P<anyo>0{3}[1-9]|\d{4})\s+(?P<hora>[1-9]|1[0-2]):(?P<minuto>[0-5]\d)\s+(?P<segundo>[ap]m))|((?P<hora>[01]\d|2[0-3]):(?P<minuto>[0-5]\d):(?P<segundo>[0-5]\d)\s+(?P<dia>[0-2]\d|3[01])/(?P<mes>0\d|1[0-2])/(?P<anyo>0{3}[1-9]|\d{4}))"
|
||||||
|
I = re.compile(i, flags=re.IGNORECASE)
|
||||||
|
|
||||||
|
R = r"( *(?P<Grados1>([0-2][0-9][0-9])|(3[0-5][0-9]))(?P<Minutos1>[0-6][0-9])(?P<Segundos1>[0-5][0-9]\.\d{4})(?P<Letra1>(N|S))(?P<Grados2>([0-2][0-9][0-9])|(3[0-5][0-9]))(?P<Minutos2>[0-5][0-9])(?P<Segundos2>[0-5][0-9]\.\d{4})(?P<Letra2>(W|E)) *)|( *(?P<Grados1>((1[0-9][0-9])|(2[0-9][0-9])|(3[0-5][0-9])|\d{2}|\d{1}))° *(?P<Minutos1>([0-5][0-9])|[0-9])' *(?P<Segundos1>(([0-5][0-9])|[0-9])\.\d{4})\" *(?P<Letra1>(N|S)) *, *(?P<Grados2>((1[0-9][0-9])|(2[0-9][0-9])|(3[0-5][0-9])|\d{2}|\d{1}))° *(?P<Minutos2>([0-5][0-9])|[0-9])' *(?P<Segundos2>(([0-5][0-9])|[0-9])\.\d{4})\" *(?P<Letra2>(W|E)) *)|( *((?P<Signo1>[+\- ]?)(?P<Coord1>(([1-8]?[0-9])\.\d+)|90)) *, *((?P<Signo2>[+\- ]?)(?P<Coord2>([1][0-7][0-9]\.\d+)|([1-9]?[0-9]\.\d+))|90) *)"
|
||||||
|
P = re.compile(R)
|
||||||
151
sesion6.py
Normal file
151
sesion6.py
Normal file
@@ -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<parte1>\d{3})-(?P<parte2>\d{3})-(?P<parte3>\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<letrainicio>[X-Z])*(?P<numero>\d{7}))|(?P<numero>\d{8}))-(?P<letrafinal>[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"((?P<anyo>0{3}[1-9]|\d{4})-(?P<mes>0\d|1[0-2])-(?P<dia>[0-2]\d|3[01])\s+(?P<hora>[0-1]\d|2[0-4]):(?P<minuto>[0-5]\d))|((?P<mes>january|february|march|april|may|june|july|august|september|october|november|december)\s+(?P<dia>\d|[12]\d|3[01]),\s+(?P<anyo>0{3}[1-9]|\d{4})\s+(?P<hora>[1-9]|1[0-2]):(?P<minuto>[0-5]\d)\s+(?P<segundo>[ap]m))|((?P<hora>[01]\d|2[0-3]):(?P<minuto>[0-5]\d):(?P<segundo>[0-5]\d)\s+(?P<dia>[0-2]\d|3[01])/(?P<mes>0\d|1[0-2])/(?P<anyo>0{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<Grados1>([0-2][0-9][0-9])|(3[0-5][0-9]))(?P<Minutos1>[0-6][0-9])gi(?P<Segundos1>[0-6][0-9]\.\d{4})(?P<Letra1>[N|S])(?P<Grados2>([0-2][0-9][0-9])|(3[0-5][0-9]))(?P<Minutos2>[0-6][0-9])(?P<Segundos2>[0-6][0-9]\.\d{4})(?P<Letra2>[W|E]) *)|( *(?P<Grados1>((1[0-9][0-9])|(2[0-9][0-9])|(3[0-5][0-9])|\d{2}|\d{1}))° *(?P<Minutos1>([0-5][0-9])|[0-9])' *(?P<Segundos1>(([0-5][0-9])|[0-9])\.\d{4})\" *(?P<Letra1>(N|S)) *, *(?P<Grados2>((1[0-9][0-9])|(2[0-9][0-9])|(3[0-5][0-9])|\d{2}|\d{1}))° *(?P<Minutos2>([0-5][0-9])|[0-9])' *(?P<Segundos2>(([0-5][0-9])|[0-9])\.\d{4})\" *(?P<Letra2>(N|S)) *)|( *(?P<Coord1>[(+|\-| ](([1-8]?[0-9]\.\d+)|90)) *, *(?P<Coord2>[(+|\-| ](([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("proyecto/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>-sphone (?P<telefono>\S*) (?P<fichero>\S*))|(?P<stime>-stime (?P<inicio>\S*) (?P<final>\S*) (?P<fichero>\S*))|(?P<n>n (?P<fichero>\S*))|(?P<snif>-snif (?P<nif>\S*) (?P<fichero>\S*))'
|
||||||
|
A = re.compile(argumentos)
|
||||||
|
match = A.match(arg_prueba)
|
||||||
|
print(type(match))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user