Python error when comparing strings - python

I have a problem with this code, it's not comparing the strings and I don't know where else I can look to know the problem:
Please somebody help me, it reads de files, everything is there but it doesn't compare
# strings.py
def leerArchivo(nombre_archivo):
archivo=open(nombre_archivo,'r')
datos = archivo.read()
datos_separados = datos.split()
archivo.read()
archivo.close()
return datos_separados
def leerArchivo_Lineas(nombre_archivo):
archivo=open(nombre_archivo,'r')
lineas = list(archivo)
return lineas
def estaElementoEn(elemento,lista):
for token in lista:
print("Comparando ",type(token)," con: ",type(elemento))
## HERE IT'S NEVER COMPARING!!
if token == elemento:
return True
return False
def esNombre(palabra,lista):
if palabra[0]=='_':
for i in range(1,len(palabra)):
letra = palabra[i]
encontro=False
j=0
while j<len(lista) and not encontro:
if letra == lista[j]:
encontro=True
j=j+1
if not encontro:
return False
return True
return False
##1. Leer archivos:
palabrasReservadas = leerArchivo_Lineas('palabrasReservadas.txt')
tiposDatos = leerArchivo_Lineas('tiposDatos.txt')
simbolos = leerArchivo_Lineas('simbolos.txt')
simbolosNombres = leerArchivo_Lineas('simbolosNombres.txt')
##2. Leer lineas archivo con el codigo
codigo = leerArchivo('codigo.txt')
errores =0;
## Lee cada línea del archivo.
for i in range(0,len(codigo)):
palabras = codigo[i].split(' ') ## Separa cada elemento de la linea
for palabra in palabras:
if estaElementoEn(palabra,tiposDatos):
##print ("Error en la línea: ",i+1," en el elemento: ",palabra)
print("ESTA")

The issue is that when you read files and create a list from it as -
def leerArchivo_Lineas(nombre_archivo):
archivo=open(nombre_archivo,'r')
lineas = list(archivo)
return lineas
The newlines at the end are still present in each element of the list. So most probably when you are doing the comparison, you are comparing against the string with newline in it , something like -
'string\n'
You can strip both elements before comparing-
def estaElementoEn(elemento,lista):
for token in lista:
print("Comparando ",type(token)," con: ",type(elemento))
## HERE IT'S NEVER COMPARING!!
if token.strip() == elemento.strip():
return True
return False

Related

delete an element of a tuple within a list [Python, Tuples, Lists]

I am creating a menu for a billing program with tuples inside lists, how would you do to delete a data requested by the user deleting all its values?
menu = """
(1) Añadir Cliente
(2) Eliminar Cliente
(3) Añadir Factura
(4) Procesar facturacion del mes
(5) Listar todos los clientes
(6) Terminar
"""
lista_nom =[]
list_borra2 = []
ventas = []
while True:
print(menu)
opc = input("Escriba una opcion: ")
opc = int(opc)
if opc == 1:
nombre = input("Escribe el nombre del cliente: ")
cif = input('Escribe el cif de cliente: ')
direccion = input("Escribe el direccion de cliente: ")
lista_nom1 = (nombre,cif,direccion)
lista_nom.append(lista_nom1)
print(lista_nom)
#print(lista_nom1)mismo dato en tupla
if opc == 2:
nombre = input('Escriba el nombre del cliente a borrar: ')
for nombre in lista_nom[0]:
lista_nom.remove[(nombre)]
else:
print('No existe el cliente con el nombre', nombre)
# for nom in range(len(lista_nom)):
# for eli in range(len(lista_nom[nom])):
# if lista_nom[nom][eli][0] == nombre:
# del lista_nom[nom:nom+1]
# print(lista_nom)
I have tried to access the element with nested for but it simply does nothing.
try to create a new list to store the deleted data and then install it in the first list with the main values to be deleted
# list_borra2.append(nombre)
# for nom in range(len(lista_nom)):
# for eli in range(len(lista_nom[nom])):
# if lista_nom[nom][eli][0] == nombre:
# del lista_nom[nom:nom+1]
# print(lista_nom)
# lista_nom.remove(nombre)
# list_borra2 += lista_nom
# # print(list_borra2)
# print(list_borra2)
Instead of deleting an element, what is not possible inside of tuples, you could define a new tuple by doing
nom_remove = lista_nom[:nom] + lista_nom[(nom+1):]
At the end I resolved the problem with this, like the other guy tell me the tuples are immutable so I need to go inside the list and i can access to the tuple:
if opc == 2:
nombre = input('Escriba el nombre del cliente a borrar: ')
vivo = 0
for kilo in ventas:
vivo = ventas[kilo].count(nombre)
if vivo == 0:
for nom in range(len(lista_nom)):
if lista_nom[nom].count(nombre)>0:
del lista_nom[nom:nom+1]
print(lista_nom)
break

How to register and than search a value in CSV file?

I'm trying to register an user and then read the data I just appended. It looks like the csv file is appending the value, but it's not saving it. But this is awkward, because I used the "with open" function at the "registered" function.
def is_registered(ID): #OK
df = read_any_csv(users_path)
x = df.loc[df["ID"] == ID]
if x.empty:
return False
else:
return True
#faz o cadastro do usuario
def register(ID): #OK
x = str(input("Escreva seu nome: "))
name = x.title()
section = int(input("Digite seu setor(111/112/113): "))
data = [name,ID,section]
with open (users_path,'a') as file:
writer = csv.writer(file)
writer.writerow(data)
def start():
#Se o usuario estiver registrado, da as boas vindas a ele, caso nao, registra ele e depois da as boas vindas
if is_registered(ID) == True: #OK
current_user = users_df.loc[users_df["ID"] == ID]
name = current_user["NAME"]
name2 =(name.to_string(index=False))
section = current_user["SECTION"]
print(f"Ola, {name2}, bem vindo ao programa de treinamento Mercedes Benz Brasil!\n")
videos = videos_to_watch(section)
print("Esses sao os videos que faltam serem assistidos:\n")
print(*videos,sep = '\n')
else: #OK
register(ID)
users_df.to_csv("Users.csv",index = False)
current_user = users_df.loc[users_df["ID"] == ID]
print(current_user)
But the csv can't find the data, the result that I got is that:
Digite o ID: aaaaa
Escreva seu nome: leo
Digite seu setor(111/112/113): 113
Empty DataFrame
Columns: [NAME, ID, SECTION]
Index: []
What I actually want is:
Digite o ID: 5DBEF04B
Escreva seu nome: Raul Lopes Camina
Digite seu setor(111/112/113): 113
Ola, Raul Lopes Camina, bem vindo ao programa de treinamento Mercedes Benz Brasil!
You write new data to file but this can't change original users_df and you would have to read it again (instead of write again)
register(ID)
users_df = pd.read_csv("Users.csv") # <-- read instead of write
current_user = users_df.loc[users_df["ID"] == ID]
print(current_user)
Or you should first add to users_df and later save it with to_csv - and then you don't have to read it again.
def register(ID): # OK
global users_df # need it to add to external variable
name = str(input("Escreva seu nome: "))
name = name.title()
section = int(input("Digite seu setor(111/112/113): "))
data = pd.DataFrame({'NAME': [name], 'ID': [ID], 'SECTION': [section]})
users_df = pd.concat([users_df, data]) # <-- add to original `users_df`
users_df.to_csv("Users.csv", index=False)
and later
register(ID)
# without `to_csv()` and `read_csv()`
current_user = users_df.loc[users_df["ID"] == ID]
print(current_user)

How I can say a specific line of text that I have list under a class?

I'm trying to make a graphic novelwith Object-oriented programming.
Actually, I'm focused on the battle part.
For some reason, the part where it's suppose to print a specific line it does not work, it would pass without doing anything, or I would get an error.
#Error:
Traceback (most recent call last):
File "C:\Users\Ester\Desktop\Mercy or kill\Gamefalse.py", line 128, in <module>
batalla_f1()
File "C:\Users\Ester\Desktop\Mercy or kill\Gamefalse.py", line 94, in batalla_f1
monstruo_escogido.frase_entre_atzar(7,9)
File "C:\Users\Ester\Desktop\Mercy or kill\mercy_kill_classes.py", line 51, in frase_entre_atzar
entre_atzar = self.frases.random.randrange (a,b)
AttributeError: 'list' object has no attribute 'random'
#Code:
Drah_krow=Personaje("Drah Krow","monstruo",12,12,5,1,1)
Drah_krow.mostrar_todo()
Drah_krow.afegeix_frase("Señor de mediana edad con un cuchillo clavado bajo el cuello... Parece desorientado.")
Drah_krow.afegeix_frase("Drah Krow- Echo de menos a alguien...")
Drah_krow.afegeix_frase("Drah Krow- ¿Quien era? ¿Eras tú?.")
Drah_krow.afegeix_frase("Drah Krow- Mi jefe me ordena cosas extrañas...")
Drah_krow.afegeix_frase("Drah Krow- Quiere que te mate...")
Drah_krow.afegeix_frase("Drah Krow- Oh, ya me acordé...¿Dondè estarà mi hija?")
Drah_krow.afegeix_frase("Drah Krow- Me siento tan perdido que podría morir...")
Drah_krow.afegeix_frase("Drah Krow- Me gustaria ir a la playa con el... ¿O era ella?")
Drah_krow.afegeix_frase("Drah Krow- ¿Me conoces?")
Drah_krow.afegeix_frase("Drah Krow- No se donde estoy...")
Drah_krow.mostra_frases()
prota = Humano("Prota")
def batalla_f1():
Drah_krow=Personaje("Drah Krow","fantasma",20,1,0)
monstruo_escogido=Drah_krow
prota.mostrar_todo()
print("")
monstruo_escogido.mostrar_todo()
print("")
z=0
d=0
q=0
inici_hp = prota.hp
inicim_hp = monstruo_escogido.hp
while not((prota.hp<=0) or (monstruo_escogido.hp<=0)):
print("Es tu turno:")
z=z+1
i = input("1.atacar 2.defender 3.Comprender")
if(i=="1"):
print("Tu- Atacas:")
a = (prota.atk - monstruo_escogido.defe)
if (prota.atk < monstruo_escogido.defe): # Ataque del prota es mas pequeño que la defensa del monstruo = anular ataque del prota
a = 0
if (a > monstruo_escogido.hp): # Vida del monstruo = 0 (Evitar numeros negativos en la vida del monstruo)
a = monstruo_escogido.hp
print ("Haces",a," de daño.")
monstruo_escogido.hp = (monstruo_escogido.hp-a)
print("La vida del mosntruo se reduce a",monstruo_escogido.hp)
d=d+1
prota.mostrar_todo()
monstruo_escogido.mostrar_todo()
elif(i=="2"):
print ("prota defiende")
a= random.randrange(5,50)
if(prota.hp == inici_hp):
print("Tu hp ya está al máximo.")
elif (prota.hp < inici_hp):
print (a)
if((a+prota.hp)> inici_hp):#si la suma del hp mas lo que se cura es mas grande que el hp original:
aa=(inici_hp -(a+prota.hp)) #restas el nuevo hp - hp original
prota.hp = inici_hp
print ("Te curas:",aa,"hp")
print("Tu hp sube a",prota.hp)
print("")
elif((a+prota.hp)<inici_hp):
print ("Te curas",a,"hp")
prota.hp = (prota.hp + a)
print("Tu hp sube a",prota.hp)
print("")
prota.mostrar_todo()
print("")
monstruo_escogido.mostrar_todo()
elif(i=="3"):
print("Prota actua:")
a=input("1.Observar 2.Hablar 3.Llorar")
if(a=="1"):
print("Tu- Observas detalladamente:")
monstruo_escogido.digues_frase_concreta(0)
elif(a=="2"):
print("Tu- Le dice que no quieres pelear...")
if((z==0) and (d==0)):
monstruo_escogido.digues_frase_concreta(1)
if((z==0) and (d!=0)):
monstruo_escogido.digues_frase_concreta(3)
if((z==2) and (d==0)):
monstruo_escogido.digues_frase_concreta(2)
q=1
if((z==2) and (d!=0)):
monstruo_escogido.digues_frase_concreta(4)
elif((z!=0) or (z!=2)):
monstruo_escogido.frase_entre_atzar(7,9)
if(q==1):
monstruo_escogido.digues_frase_concreta(5)
elif(a=="3"):
print ("Drah Krow parece confundido...")
prota.incrementa_hp(5)
print ("Te recuperas por 5 hp.")
if not((prota.hp<=0) or (monstruo_escogido.hp<=0) or (q==1)):
print("")
print("Es el turno del monstruo:")
print("")
print("Monstruo ataca:")
b= (monstruo_escogido.atk - prota.defe)#Daño real producido al final
if (monstruo_escogido.atk < prota.defe ): # Anular ataque del monstruo
b = 0
if (b > prota.hp):
b = prota.hp
print ("Monstruo hace",b," de daño.")
prota.hp = (prota.hp-b)
print("")
prota.mostrar_todo()
print("")
monstruo_escogido.mostrar_todo()
print ("")
if (prota.hp >0):
print ("Tu ganas.")
prota.kill =(prota.kill+1)
elif (q==1):
print ("Drah Krow parece volver un poco en si.")
print ("Drak Krow desaparece tras un destello de luz blanca.")
prota.mercy = (prota.mercy +1)
elif(prota.hp == 0):
print("Game Over")
batalla_f1()
#Class:
import random
class Personaje():
def __init__(self, nom, especie="desconeguda", hp=0, atk=0, defe=0,mercy=0, kill=0):
self.nom= nom
self.especie= especie
self.hp = hp
self.atk = atk
self.defe = defe
self.mercy=mercy
self.kill=kill
self.frases=[]
def mostrar_todo(self): #mostra tots els atributs d'un personatge excepte frases
print("Nom: ", self.nom)
print("Especie:", self.especie)
print("Hp:",self.hp)
print("Atk:",self.atk)
print("Def:",self.defe)
def mostrar_todo_prota(self):
print("Nom: ", self.nom)
print("Especie:", self.especie)
print("Hp:",self.hp)
print("Atk:",self.atk)
print("Def:",self.defe)
print("Mercy:",self.mercy)
print("Kill:",self.kill)
def incrementa_hp(self, quantitat): #mètodes per incrementar els diferents atributs
self.hp = self.hp + quantitat
def incrementa_atk(self, quantitat):
self.atk = self.atk + quantitat
def incrementa_defe(self, quantitat):
self.defe = self.defe+ quantitat
def incrementa_mercy(self, quantitat):
self.mercy = self.mercy + quantitat
def incrementa_kill(self, quantitat):
self.kill = self.kill + quantitat
def afegeix_frase(self, frase): #mètode per afegir frases a la llista del personatge en concret
self.frases.append(frase)
def mostra_frases(self): #mètode per mostrar totes les frases del personatge
for frase in self.frases:
print(frase)
def digues_frase(self): #dir una frase de la llista a l'atzar
if (len(self.frases)!= 0):
frase = random.choice(self.frases)
else:
frase= ("...")
print(frase)
def digues_frase_concreta(self, ordre):
if(ordre<(len(self.frases))):
print(self.frases[ordre])
def frase_entre_atzar(self,a,b):
entre_atzar = self.frases.random.randrange (a,b)
print (entre_atzar)
def ataca(self,oponent):
print(self.nom,"ATACA A", oponent.nom)
if (self.atk > oponent.defe):
oponent.hp = (oponent.hp-1)
print("Li has fet mal a", oponent.nom)
else:
print("No li has fet mal a", oponent.nom)
class Humano(Personaje):
def __init__(self, nom):
super().__init__(nom) #hereda el nom de la classe Personatge
self.especie="humano" #fixa els atributs propis de la classe Humano
self.hp=30
self.atk=15
self.defe=15
self.mercy=0
self.kill=0
class Bestia(Personaje):
def __init__(self, nom):
super().__init__(nom)
self.especie="bestia"
self.hp=15
self.atk=30
self.defe=15
self.mercy=0
self.kill=0
class DemiHumano(Personaje):
def __init__(self, nom):
super().__init__(nom)
self.especie="demi-humano"
self.hp=15
self.atk=15
self.defe=30
self.mercy=0
self.kill=0
I can't understand why it wok the part of "1.atacar 2.defender", but not the part of "3.Comprender".
Could you help me, please?
Also, Do you know any way to count the turns while the battle is going on, to say a different phrase each time the loop is restarted before one of the two characters dies?
(Sorry if some parts are in Spanish, if there something you don't understand, feel free to ask.)
As the error message states, here's the line giving you error:
entre_atzar = self.frases.random.randrange (a,b)
random is not a data member of the the class of which frases is a member (which appears to a list) so you cannot use the dot operator to call a data member of the class that simply doesn't exist.
Normally, random.randrange(a,b) will return a random number in the range between a and b.
So you have two options:
1) Get a number in a random range between a and b and then use that get the value at that index in the list:
entre_atzar = self.frases[random.randrange(a,b)]
2) Simply get a random value from a sub-list of the original list in that range:
entre_atzar = random.choice(self.frases[a:b])
I recommend the latter method, since I consider it to be cleaner and more intuitive, but both will yield the same result.

why is the second loop never executed ?

Hi, i am actually working on a python program and i need to read a csv file and use data.append(line) to fill a data Array.
I wrote this following part of the program :
print "Lecture du fichier", table1
lecfi = csv.reader(open(table1,'r'),skipinitialspace = 'true',delimiter='\t')
# delimiter = caractere utilisé pour séparer les différentes valeurs
tempSize = 0
tempLast = ""
oldSize = 0
#on initialise la taille du fichier et la derniere ligne du fichier
if os.path.exists(newFilePath):
tempSize = os.path.getsize(newFilePath)
else:
tempSize = 0
if os.path.exists(newFilePath) and tempSize != 0:
#Si le fichier tampon n'existe pas, on le créer
#Lecture du fichier tampon
lecofi = csv.reader(open(newFilePath,'r'),skipinitialspace = 'true',delimiter='\t')
csvFileArray = []
for lo in lecofi:
csvFileArray.append(lo)
tempLast = str(csvFileArray[0])
tempLast = tempLast[2:-2]
oldSize = csvFileArray[1]
print "Tempon de Last : ", tempLast
print "Taille du fichier : ", str(oldSize)
#on récupere la ligne représentant la derniere ligne de l'ancien fichier
else:
#si le fichier n'existe pas, on lui laisse cette valeur par défaut pour le traitement suivant
tempLast = None
# remplissage des données du fichier pulse dans la variable data
cpt = 0
indLast = 0
fileSize = os.path.getsize(table1)
if oldSize != fileSize:
for lecline in lecfi:
cpt = cpt + 1
last = str(lecline)
if tempLast != None and last == tempLast:
print "TEMPLAST != NONE", cpt
indLast = cpt
print "Indice de la derniere ligne : ", indLast
print last, tempLast
print "Variable indLast : ", indLast
i = 0
for co in lecfi:
print "\nCOOOOOOO : ", co
if i == indLast:
data.append(co[0])
i=i+1
for da in data:
print "\n Variable data : ", da
now look at the prints :
Lecture du fichier Data_Q1/2018-05-23/2018-5-23_13-1-35_P_HOURS_Q1
Tempon de Last : ['(2104.72652']
Taille du fichier : ['20840448']
TEMPLAST != NONE 317127
Indice de la derniere ligne : 317127
['(2104.72652'] ['(2104.72652']
Variable indLast : 317127
It seems like the program doesn't care about what's following my for loop. I assume that it can be a really basic mistake but i can't get it.
Any help ?
You are trying to iterate over the CSV twice without reseting it. this is the reason your data array is empty.
The first time you actually iterates over the file:
for lecline in lecfi:
The second time, the original iterator already reached it's end and is empty:
for co in lecfi:
As mentioned in the comments by Johnny Mopp one possible solution is using the following method:
Python csv.reader: How do I return to the top of the file?
Hope this explains your issue.
Here:
for lecline in lecfi:
cpt = cpt + 1
# ...
you are reading the whole file. After this loop, the file pointer is at the end of the file and there's nothing more to be read. Hence here:
i = 0
for co in lecfi:
# ...
this second loop is never executed, indeed. You'd need to either reset the file pointer, or close and reopen the file, or read it in a list right from the start and iterate over this list instead.
FWIW, note that opening files and not closing them is bad practice and can lead to file corruption (not that much in your case since you're only reading but...). A proper implementation would look like:
with open(table1) as tablefile:
lecfi = csv.reader(tablefile, ....)
for lecline in lecfi:
# ....
tablefile.seek(0)
for lecline in lecfi:
# ....
Also, this:
lecofi = csv.reader(open(newFilePath,'r'),skipinitialspace = 'true',delimiter='\t')
csvFileArray = []
for lo in lecofi:
csvFileArray.append(lo)
would be better rewritten as:
with open(newFilePath) as newFile:
lecofi = csv.reader(newFile, ...)
csvFileArray = list(lecofi)

Python XML DOM collecting elements data

I was trying to retrieve some info of an XML tag with Python. My goal is to have a dictionary which saves for each situation tag id, all child data, but I don't know how to deal with the fact that extract data from text nodes.
My code:
from xml.dom.minidom import *
import requests
print("GETTING XML...")
resp = requests.get('http://infocar.dgt.es/datex2/dgt/SituationPublication/all/content.xml', stream = True) #XML that I need
if resp.status_code != 200:
raise ApiError('GET /tasks/ {}'.format(resp.status_code))
print("XML RECIBIDO 200 OK")
#resp.raw.decode_content = True
print("GUARDANDO XML")
with open("DGT_DATEX.xml", "wb") as handle:
for data in (resp.iter_content()):
handle.write(data)
print("XML GUARDADO")
print("INICIANDO PARSEO..")
dom3 = parse("DGT_DATEX.xml")
print(dom3)#memory dir
print("DATEX PARSEADO")
def getText(nodelist):
dict = {}
listofdata = list()
for node in nodelistofPayloadTag:
if node.nodeType != node.TEXT_NODE:
dict[node.getAttribute('id')] = listofdata
listofdata = goDeep(node.childNodes ,listofdata)
print(str.format("El diccionario antes de ser retornado es {0}", dict))
return dict
def goDeep(childsOfElement, l):
for i in childsOfElement:
if i.nodeType != i.TEXT_NODE:
goDeep(i.childNodes, l)
else:
l.append(i.data)
return l
def getSituation(payloadTag):
getText(payloadTag.childNodes)
def getPayLoad(dom):
print(str.format("Tag to be processed:{0}",dom.getElementsByTagNameNS('*', 'payloadPublication')[0]))
getSituation(dom.getElementsByTagNameNS('*', 'payloadPublication')[0])
print(str.format("Verificando que el dato retornado es un diccionario, {0}, y contiene {1}", type(getPayLoad(dom3)), getPayLoad(dom3)))
I came to this code, is it what you were looking for?
def getText(element):
return element.data.encode('utf-8').strip()
def getPayLoad(dom):
attrs = ['confidentiality', 'informationStatus', 'situationRecordCreationReference', 'situationRecordCreationTime', 'situationRecordVersion', 'situationRecordVersionTime', 'situationRecordFirstSupplierVersionTime', 'probabilityOfOccurrence', 'sourceCountry', 'sourceIdentification', 'validityStatus', 'overallStartTime', 'overallEndTime', 'impactOnTraffic', 'locationDescriptor', 'tpegDirection', 'latitude', 'longitude', 'tpegDescriptorType', 'from']
for index, node in enumerate(dom.getElementsByTagNameNS('*', 'situation'), 1):
print("\nSituation ID: {0} numero {1}".format(getAttributeID(node), index))
for attr in attrs:
key = node.getElementsByTagNameNS('*', attr)
if key:
value = getText(key[0].firstChild)
if value:
print('{0}: {1}'.format(attr, value))
Here is the way which allow me to collect data from childs, thanks
import xml.etree.ElementTree as ET
from xml.dom.minidom import *
import requests
print("GETTING XML...")
resp = requests.get('http://infocar.dgt.es/datex2/dgt/SituationPublication/all/content.xml', stream = True) #XML that I need
if resp.status_code != 200:
raise ApiError('GET /tasks/ {}'.format(resp.status_code))
print("XML RECIBIDO 200 OK")
#resp.raw.decode_content = True
print("GUARDANDO XML")
with open("DGT_DATEX.xml", "wb") as handle:
for data in (resp.iter_content()):
handle.write(data)
print("XML GUARDADO")
print("INICIANDO PARSEO..")
dom3 = parse("DGT_DATEX.xml")
print(dom3)#memory dir
print("DATEX PARSEADO")
def getAttributeID(element):
return element.getAttribute('id')
def getText(element):
return element.data
def getPayLoad(dom):
dict = {}
index = 1 #esto sirve para relacionar los atributos con el situation que les corresponde
indexRecord = 1 #esto sirve para relacionar los atributos con el situationRecord que les corresponde
for i in dom.getElementsByTagNameNS('*', 'situation'):
#Por cada situation del XML vamos a sacar el situation id y todos los campos que pertecen a este de la siguiente manera
print(str.format("Situation ID: {0} numero {1}", getAttributeID(i), index))
print(getText(dom.getElementsByTagNameNS('*','confidentiality')[index].firstChild))#por ejemplo aquí, se coge el first text de la lista de atributos confidentiality dado el index, que nos indica la relacion con el situation
print(getText(dom.getElementsByTagNameNS('*', 'informationStatus')[index].firstChild))
for record in dom.getElementsByTagNameNS('*', 'situation')[index].childNodes:#buscamos el hijo del corespondiente situation que tenga un ID, lo que nos deveulve elsituationRecord
if record.nodeType != record.TEXT_NODE:
print(str.format("SituationRecord ID: {0} numero {1}", getAttributeID(record), indexRecord))
print(getText(dom.getElementsByTagNameNS('*', 'situationRecordCreationReference')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'situationRecordCreationTime')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'situationRecordVersion')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'situationRecordVersionTime')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'situationRecordFirstSupplierVersionTime')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'probabilityOfOccurrence')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'sourceCountry')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'sourceIdentification')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'validityStatus')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'overallStartTime')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'overallEndTime')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'impactOnTraffic')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'locationDescriptor')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'tpegDirection')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'latitude')[indexRecord].firstChild))
print(getText(dom.getElementsByTagNameNS('*', 'longitude')[indexRecord].firstChild))
print(str.format("VALUE FIELD: {0}", getText(dom.getElementsByTagNameNS('*', 'descriptor')[indexRecord].firstChild)))
indexRecord = indexRecord + 1
index = index + 1
getPayLoad(dom3)

Categories

Resources