Python XML DOM collecting elements data - python

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)

Related

manage memory allocation exemple project

so i have this script but i dont know how it worsk can someone please explain it to me , all what i know is that we have two types pf used super user and normal user each one got many taskss
that we excecute after extracting from a file.txt
# Permet de mieux gérer le typing (définition des types lors de la signature fonction)
from future import annotations
# Permet de créer des classes héritant d'énum pour réaliser des énumérations
from enum import Enum
# Gère le multithreading
import threading
# Mise en pause du programme via time.sleep()
import time
# Lecture de la mémoire utilisée
import os, psutil
# Interface graphique
import turtle
import tkinter as tk
from tkinter import ttk
# Shuffle permet de mélanger une liste (utilisé pour la liste des story)
from random import shuffle
__FILENAME__ = "stories.txt"
__KO_SIZE_BYTE__ = 1024
__TIME_TASK_S__ = 5
__NUMBER_BLOCKS_BY_TASK__ = 5
# Booléen permettant de savoir si un super utilisateur a pris la main (mise en pause automatique des utilisateurs normaux)
is_locked_for_super_user = False
### Définition de la classe Block ###
# number_of_block : Nombre de block alloué
# state : status du block (Block.State.FREE ou Block.State.BUSY)
# data : data que le block va stocker (story)
# next_block : reférence du prochaine block
class Block:
_SIZE_ = 512 * __KO_SIZE_BYTE__
class State(Enum):
FREE = 0
BUSY = 1
def __init__(self, number_of_blocks : int, state : Block.State, data : str, next_block : Block = None):
self.number_of_blocks = number_of_blocks
self.state = state
self.data = bytearray(data, encoding="utf-8")
self.data.extend(bytearray(int((Block._SIZE_ * number_of_blocks )- len(data)), ))
self.next_block = next_block
def add(self,next_block : Block, index : int = 1) -> int:
if self.next_block:
return self.next_block.add(next_block, index + 1)
else:
self.next_block = next_block
return index
### Définition d'une classe MemoryBlock qui représente une liste chainée ###
# block : premier block de la liste chainée
class MemoryBlock:
def __init__(self, block : Block = None ):
self.block = block
def __getitem__(self, key):
if key == 0:
return self.block
item = self.block.next_block
for _ in range(1, key):
item = item.next_block
return item
def add(self, block : Block) -> int:
# manage empty block
if not self.block:
self.block = block
return 0
return self.block.add(block)
def remove(self, key):
if key == 0:
self.block = self.block.next_block
else:
self[key - 1].next_block = self[key].next_block
def size(self) -> int:
if not self.block:
return 0
size = 1
current_block = self.block
while current_block.next_block:
current_block = current_block.next_block
size+= 1
return size
### Classe Task ###
# lib_task : Libellé de la tache
# time_task : Temps d'éxécution de la tache en seconde
# mem_task : taille allouée à la tache
# level_task : Priorité de la tache (Task.Priority.HIGH ou Task.Priority.LOW)
# state_task : Etat de la tache (Task.State.ACTIVE ou Task.State.SLEEPING)
# treeView : arbre de l'interface graphique qui affiche l'éxécution des taches
# story : Chaine de caractère à afficher par la tâche en time_task secondes
# block_memory : liste chainée de block
class Task(threading.Thread):
class Priority(Enum):
HIGH = 0
LOW = 1
class State(Enum):
ACTIVE = 0
SLEEPING = 1
def __init__(self, lib_task : str, time_task : int, mem_task : int, level_task : Priority, state_task : State, treeview : ttk.Treeview, story : str, block_memory : MemoryBlock):
self.lib_task = lib_task
self.time_task = time_task
self.index_block = block_memory.add(Block(number_of_blocks=int(mem_task / Block._SIZE_), state= Block.State.BUSY, data = story))
self.story = story
self.block_memory = block_memory
self.level_task = level_task
self.state_task = state_task
self.treeview = treeview
self.block_memory = block_memory
threading.Thread.__init__(self)
def run(self):
self.state_task = Task.State.ACTIVE
data_to_display = self.block_memory[self.index_block].data.decode()[0:len(self.story)]
nb_to_display_each_sec = int(len(data_to_display) / self.time_task)
self.treeview.insert("",'end', text=self.lib_task, values = (self.lib_task, ""))
total_display_chars = nb_to_display_each_sec
global is_locked_for_super_user
for i in range(0, self.time_task + 1):
while self.level_task == Task.Priority.LOW and is_locked_for_super_user:
time.sleep(0.5)
for item in self.treeview.get_children():
if self.treeview.item(item)["text"] == self.lib_task:
self.treeview.item(item, values = (self.lib_task, data_to_display[0:total_display_chars]))
total_display_chars += nb_to_display_each_sec
break
time.sleep(1)
self.treeview.item(item, values = (self.lib_task, data_to_display))
self.state_task = Task.State.SLEEPING
self.block_memory[self.index_block].state = Block.State.FREE
### Thread permettant de gérer l'éxécution de toutes les taches ###
# memoryBlock : liste chainée de block
# stories : liste de chaine de caractères que les taches executerons
# treeView : arbre de l'interface graphique qui affiche l'éxécution des taches
class TaskManager(threading.Thread):
def __init__(self, memoryBlock: MemoryBlock, stories, priority : Task.Priority, treeView : ttk.Treeview):
self.memoryBlock = memoryBlock
self.stories = stories
self.priority = priority
self.treeView = treeView
threading.Thread.__init__(self)
def run(self):
global is_locked_for_super_user
while self.priority == Task.Priority.LOW and is_locked_for_super_user:
time.sleep(0.5)
# launch tasks
shuffle(self.stories)
tasks = []
for index, story in enumerate(self.stories):
task = Task(lib_task="task " + str(index), time_task=__TIME_TASK_S__, mem_task=Block._SIZE_ * __NUMBER_BLOCKS_BY_TASK__, level_task=self.priority, state_task=Task.State.SLEEPING, treeview=self.treeView, story=story, block_memory=self.memoryBlock)
task.start()
tasks.append(task)
# une tache dormante, une fois arrivé son tour d’exécution, elle donne la main à la suivante.
while task.state_task == Task.State.SLEEPING:
time.sleep(0.1)
# Wait until tasks are finished
for t in tasks:
t.join()
### Récupère la mémoire utilisée ###
# Retourne la mémoire utilisée en Mo
def get_memory_usage():
return psutil.Process(os.getpid()).memory_info().rss / __KO_SIZE_BYTE__ / 1024 # Mo
### Lancée par Thread dans le but de superviser le lancement des taches ###
# memoryBlock : liste chainée de block
# stories : liste de chaine de caractères que les taches executerons
# treeView : arbre de l'interface graphique qui affiche l'éxécution des taches
def launch_task_manager(memoryBlock : MemoryBlock, stories, priority : Task.Priority, treeView : ttk.Treeview):
# Clear treeview
for row in treeView.get_children():
treeView.delete(row)
global is_locked_for_super_user
if priority == Task.Priority.HIGH:
is_locked_for_super_user = True
taskManager = TaskManager(memoryBlock, stories, priority, treeView)
taskManager.start()
taskManager.join()
# garbage collector
for i in range(memoryBlock.size() -1, -1, -1):
if memoryBlock[i].state == Block.State.FREE:
memoryBlock.remove(i)
if priority == Task.Priority.HIGH:
is_locked_for_super_user = False
### Extrait toutes les lignes à partir d'un fichier ###
# filename : chemin vers le fichier à lire
# Retourne une liste des lignes lues
def read_stories(filename : str):
story = open(filename, 'r')
return [line.rstrip("\n") for line in story.readlines()]
### Supervise la mémoire utilisée et de met à jour l'interface ###
# memory_bar : Jauge de mémoire de l'interface
# memory_desc : Champs label de l'interface descrivant la mémoire utilisé
def monitor_interface(memory_bar : ttk.Progressbar, memory_desc : tk.Text):
try:
max_bar = 0
memory_bar["maximum"] = int(get_memory_usage())
while True:
memory_usage = memory_usage = int(get_memory_usage())
memory_bar["value"] = memory_usage
if memory_usage >= max_bar:
max_bar = memory_usage
memory_bar["maximum"] = max_bar
memory_desc["text"] = str(memory_usage) + ' Mo utilisés / ' + str(max_bar) + ' Mo maximum utilisés'
time.sleep(1)
except Exception:
return
def main():
# initialize head list empty
memoryBlock = MemoryBlock()
# Read story file
stories = read_stories(__FILENAME__)
turtle.title("Garbage Collector")
turtle.ht()
window = turtle.getscreen()
window.setup(800, 600)
# Create Super user Tasks field
canvas = window.getcanvas()
super_tasks_field = ttk.Treeview(canvas.master, columns=["Label", "Execution"], show="headings", height=20)
super_tasks_field.heading('Label', text='Label')
super_tasks_field.column("Label",minwidth=50,width=75)
super_tasks_field.heading('Execution', text='Execution')
super_tasks_field.column("Execution",minwidth=100,width=250)
canvas.create_window(-200, 0, window=super_tasks_field)
# Create super user button
canvas = window.getcanvas()
button = tk.Button(canvas.master, text="Super utilisateur", command=lambda: threading.Thread(target=launch_task_manager, args= (memoryBlock, stories, Task.Priority.HIGH, super_tasks_field)).start(), height=2, width=30)
canvas.create_window(-200, -250, window=button)
# Create user Tasks field
canvas = window.getcanvas()
tasks_field = ttk.Treeview(canvas.master, columns=["Label", "Execution"], show="headings", height=20)
tasks_field.heading('Label', text='Label')
tasks_field.column("Label",minwidth=50,width=75)
tasks_field.heading('Execution', text='Execution')
tasks_field.column("Execution",minwidth=100,width=250)
canvas.create_window(200, 0, window=tasks_field)
# Create user button
canvas = window.getcanvas()
button = tk.Button(canvas.master, text="Utilisateur ordinaire", command=lambda: threading.Thread(target=launch_task_manager, args= (memoryBlock, stories, Task.Priority.LOW, tasks_field)).start(), height=2, width=30)
canvas.create_window(200, -250, window=button)
# Create progress bar for memory usage
canvas = window.getcanvas()
memory_usage = ttk.Progressbar(canvas.master, orient='horizontal',mode='determinate', length=750, value=get_memory_usage(), maximum=100)
canvas.create_window(0,250, window=memory_usage)
# Create text description for memory usage
canvas = window.getcanvas()
memory_usage_description = tk.Label(canvas.master, text="", background="white")
canvas.create_window(0,275, window=memory_usage_description)
# Lancement d'un thread permettant de supervisier la mémoire utilisée
interface_monitoring_th = threading.Thread(target=monitor_interface, args=(memory_usage, memory_usage_description), daemon= False)
interface_monitoring_th.start()
window.mainloop()
if __name__ == '__main__':
main()

Error when I close a windows with GTK3/Glade/Python

I have a probleme with my interface glade. I can open my interface, no problem with that, It's work in the way I want but when I close it all the main programm stop and I have two messages in the consol
(BouclePrincipal.py:50516): Gtk-CRITICAL **: 09:01:00.615: gtk_widget_get_accessible: assertion 'GTK_IS_WIDGET (widget)' failed>
(BouclePrincipal.py:50516): Atk-CRITICAL **: 09:01:00.615: atk_object_remove_relationship: assertion 'ATK_IS_OBJECT (target)' failed
I don't understand what/where is the problem. I tried to add return true like the following
answer but it's dosn't work. Furthermore I don't know what I need to post for this problem (interface glad ? the init in python ?)
here the python code
# on importe les librairies dont nous avons besoins
import gi
import sqlite3
import Alerte
import datetime
import AjouterMedicament
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
Idutilisateur = 0
# on creer la classe pour l'interface
class AffichageEcritureIP:
# ligne de code qui se lance lorsque de l'initialisation
def __init__(self):
# on creer la fenetre à partir de l'interface glade
self.builder = Gtk.Builder()
self.builder.add_from_file('EcritureIP.glade')
self.window = self.builder.get_object('Main_Windows_IP')
# on creer des objetrs pour chaqu'une des interractions
self.builder.connect_signals(self)
# on creer les variables
self.DateIP = self.builder.get_object("DateRealisation")
self.Service = self.builder.get_object("Services")
self.NomPatient = self.builder.get_object("NomPatient")
self.PrenomPatient = self.builder.get_object("PrenomPatient")
self.Age = self.builder.get_object("Age")
self.UniteAge = self.builder.get_object("UniteAge")
self.Sexe = self.builder.get_object("Sexe")
self.Probleme = self.builder.get_object("Probleme")
self.Intervention = self.builder.get_object("Intervention")
self.ATC1 = self.builder.get_object("ClasseATC1")
self.ATC2 = self.builder.get_object("ClasseATC2")
self.ProblemeDescription = self.builder.get_object("ProblemeDescription")
self.Devenir = self.builder.get_object("DevenirIntervention")
self.RetourMedecin = self.builder.get_object("RetourMedecin")
self.Medoc1 = self.builder.get_object("Médicament1")
self.Medoc2 = self.builder.get_object("Médicament2")
self.Prescripteur = self.builder.get_object("Prescripteur")
self.Contact = self.builder.get_object("Contact")
self.CotationClinique = self.builder.get_object("CotationClinique")
self.CotationEconomique = self.builder.get_object("CotationEconomique")
self.CotationOrga = self.builder.get_object("CotationOrga")
self.Conciliation = self.builder.get_object("Conciliation")
self.Poids = self.builder.get_object("Poids")
self.RetourMedecin = self.builder.get_object("RetourMedecin")
self.DateMedecin = self.builder.get_object("DateMedecin")
self.NumIP = self.builder.get_object("NumIP")
# on affecte la date du jour à l'entrée
dateBrut = datetime.datetime.now()
DateJour = FormatDate(dateBrut.day, dateBrut.month, dateBrut.year)
self.DateIP.set_text(DateJour)
#on va creer les listes pour remplir les listes déroulantes
conn = sqlite3.connect('déclaration.db')
cursor = conn.cursor()
cursor.execute("""SELECT NomService FROM Service """)
self.ListeService = cursor.fetchall()
cursor.execute("""SELECT Description FROM Probleme """)
ListeProbleme = cursor.fetchall()
cursor.execute("""SELECT Description FROM Resolution """)
ListeResolution = cursor.fetchall()
cursor.execute("""SELECT Description FROM ATC """)
ListeATC = cursor.fetchall()
cursor.execute("""SELECT Description FROM Devenir """)
ListeDevenir = cursor.fetchall()
cursor.execute("""SELECT Description FROM Prescripteur """)
ListePrescripteur = cursor.fetchall()
cursor.execute("""SELECT Description FROM Transmission """)
ListeTransmission = cursor.fetchall()
cursor.execute("""SELECT Description FROM CotationClinique """)
ListeCotationClinique = cursor.fetchall()
cursor.execute("""SELECT Description FROM CotationEconomique """)
ListeCotationEconomique = cursor.fetchall()
cursor.execute("""SELECT Description FROM CotationOrganisationnel """)
ListeCotationOrga = cursor.fetchall()
cursor.execute("""SELECT Libelle FROM Medoc ORDER BY Libelle ASC""")
self.ListeMedoc = cursor.fetchall()
cursor.execute("""SELECT Libelle FROM Sexe """)
ListeSexe = cursor.fetchall()
cursor.execute("""SELECT Libelle FROM UniteAge """)
ListeUniteAge = cursor.fetchall()
conn.close()
# on va rajouter les services dans la liste
for service in self.ListeService:
self.Service.append_text(service[0])
# on va rajouter les problemes dans la liste
for probleme in ListeProbleme:
self.Probleme.append_text(probleme[0])
# on va rajouter les resolutions dans la liste
for resolution in ListeResolution:
self.Intervention.append_text(resolution[0])
# on va rajouter les classe ATC dans la liste
for resolution in ListeATC:
self.ATC1.append_text(resolution[0])
self.ATC2.append_text(resolution[0])
# on va rajouter les Devenir dans la liste
for resolution in ListeDevenir:
self.Devenir.append_text(resolution[0])
# on va rajouter les prescripteur dans la liste
for resolution in ListePrescripteur:
self.Prescripteur.append_text(resolution[0])
# on va rajouter le contact dans la liste
for resolution in ListeTransmission:
self.Contact.append_text(resolution[0])
# on va rajouter les cotation clinique dans la liste
for resolution in ListeCotationClinique:
self.CotationClinique.append_text(resolution[0])
# on va rajouter les cotation economique dans la liste
for resolution in ListeCotationEconomique:
self.CotationEconomique.append_text(resolution[0])
# on va rajouter les cotation Orga dans la liste
for resolution in ListeCotationOrga:
self.CotationOrga.append_text(resolution[0])
# on va rajouter les cotation Orga dans la liste
for resolution in self.ListeMedoc:
self.Medoc1.append_text(resolution[0])
self.Medoc2.append_text(resolution[0])
# on va rajouter les sexe dans la liste
for resolution in ListeSexe:
self.Sexe.append_text(resolution[0])
# on va rajouter les unite d'age dans la liste
for resolution in ListeUniteAge:
self.UniteAge.append_text(resolution[0])
#on va creer l'autocomplete pour les medicament
self.liststoreMedoc = Gtk.ListStore(str)
for s in list(sum(self.ListeMedoc,())):
self.liststoreMedoc.append([s])
self.autocompletemedoc = Gtk.EntryCompletion()
self.autocompletemedoc.set_model(self.liststoreMedoc)
self.autocompletemedoc.set_text_column(0)
self.builder.get_object("EntreMedoc1").set_completion(self.autocompletemedoc)
self.builder.get_object("EntreMedoc2").set_completion(self.autocompletemedoc)
def ClicConciliation(self, widget):
if self.Conciliation.get_label() == "Non":
self.Conciliation.set_label("Oui")
else:
self.Conciliation.set_label("Non")
def ValidationIP(self, widget):
global Idutilisateur
# on commence par verifier que les donne importante sont saisie
continuer = 0
if len(self.DateIP.get_text()) == 0:
Alerte.appelAffichageAlerte("Il faut saisir la date")
continuer = 1
if len(self.Service.get_active_text()) == 0:
Alerte.appelAffichageAlerte("Il faut saisir le service")
continuer = 1
if len(self.Age.get_text()) == 0:
Alerte.appelAffichageAlerte("Il faut saisir l'age du patient")
continuer = 1
if self.UniteAge.get_active_text() is None:
Alerte.appelAffichageAlerte("Il faut saisir l'unite de l'age du patient")
continuer = 1
if self.Sexe.get_active_text() is None:
Alerte.appelAffichageAlerte("Il faut saisir le sexe du patient")
continuer = 1
if self.Probleme.get_active_text() is None:
Alerte.appelAffichageAlerte("Il faut saisir le probleme")
continuer = 1
if self.Intervention.get_active_text() is None:
Alerte.appelAffichageAlerte("Il faut saisir l'intervention")
continuer = 1
if self.Prescripteur.get_active_text() is None:
Alerte.appelAffichageAlerte("Il faut saisir le prescripteur")
continuer = 1
if len(self.Medoc1.get_active_text()) == 0:
Alerte.appelAffichageAlerte("Il faut saisir le médicament")
continuer = 1
if self.Devenir.get_active_text() is None:
Alerte.appelAffichageAlerte("Il faut saisir le devenir de l'IP")
continuer = 1
# on creer un tableau avec les IP qui necessitent de saisir un autre médicaments
IPavecdeuxMedoc = [15, 19, 20, 21, 22, 23, 24, 25, 34]
# on rajoute 1 à l'ID car le premier de la liste à l'ID 0
IDProbleme = (self.Probleme.get_active() + 1)
if IDProbleme in IPavecdeuxMedoc and len(self.Medoc2.get_active_text()) == 0:
Alerte.appelAffichageAlerte("Il faut saisir le second médicament pour cette intervention")
continuer = 1
if continuer == 1:
pass
else:
# on va donc ajouter l'IP dans la base
global Idutilisateur
# on transformer la conciliation en 1 ou 0
if self.Conciliation.get_label() == "Non":
Conciliation = 0
else:
Conciliation = 1
#on va verifier que le/les medoc(s) saisi existe bien dans la base de donnée
# on verifie si le service fait partie de la liste
# on va transformer la liste de tuple en list pur
if self.Medoc1.get_active_text() in list(sum(self.ListeMedoc,())):
pass
else:
AjouterMedicament.appelAffichageAjoutMedicament(self.Medoc1.get_active_text(), self.ATC1.get_active(),1)
if self.Medoc2.get_active_text()=="" or self.Medoc2.get_active_text() in list(sum(self.ListeMedoc,())):
pass
else:
AjouterMedicament.appelAffichageAjoutMedicament(self.Medoc2.get_active_text(), self.ATC2.get_active(),1)
# on va chercher le code UCD et l'id du médicament
conn = sqlite3.connect('déclaration.db')
cursor = conn.cursor()
cursor.execute("SELECT id,CodeUCD FROM Medoc WHERE Libelle = ?", (self.Medoc1.get_active_text(),))
Medicament1 = cursor.fetchone()
if self.Medoc2.get_active_text() == "":
Medicament2 =[0,0]
else:
cursor.execute("SELECT id,CodeUCD FROM Medoc WHERE Libelle = ?", (self.Medoc2.get_active_text(),))
Medicament2 = cursor.fetchone()
conn.close()
# on va creer des variable pour les texte
# pour le TextViewer le texte est lié à une Buffer de Texte
# pour afficher le texte il est necessaire d'avoir le début et la fin du texte
# on creer donc le début et la fin et on l'inclut dans
iterdebut, iterfin = self.ProblemeDescription.get_bounds()
DescriptionProbleme = str(self.ProblemeDescription.get_text(iterdebut, iterfin, include_hidden_chars=True))
iterdebut2, iterfin2 = self.RetourMedecin.get_bounds()
RetourMedecin = str(self.RetourMedecin.get_text(iterdebut2, iterfin2, include_hidden_chars=True))
# on creer une liste de tuplue pour fussioner avec la liste pour inserer les donnes
IP = [(str(self.DateIP.get_text()),
Idutilisateur,
str(self.NomPatient.get_text()),
str(self.PrenomPatient.get_text()),
str(self.Age.get_text()),
self.UniteAge.get_active()+1,
self.Sexe.get_active()+1,
str(self.Poids.get_text()),
self.Probleme.get_active() + 1,
Medicament1[0],
Medicament1[1],
self.ATC1.get_active()+1,
Medicament2[0],
Medicament2[1],
self.ATC2.get_active()+1,
self.Service.get_active() + 1,
DescriptionProbleme,
self.Intervention.get_active() + 1,
self.Prescripteur.get_active() + 1,
self.Contact.get_active() + 1,
self.DateMedecin.get_text(),
self.Devenir.get_active() + 1,
self.CotationClinique.get_active() + 1,
self.CotationEconomique.get_active() + 1,
self.CotationOrga.get_active() + 1,
Conciliation,
RetourMedecin)]
# pour reussir à faire l'insertion des données avec le Update , on creer une liste avec les noms de colonne
ColonneSQL = [
"DateSaisie",
"Utilisateur",
"NomPatient",
"PrenomPatient",
"AgePatient",
"UniteAgePatient",
"SexePatient",
"Poids",
"Probleme",
"Medicament1",
"CodeUCD1",
"ATC1",
"Medicament2",
"CodeUCD2",
"ATC2",
"Service",
"DescriptionProbleme",
"Intervention",
"Prescripteur",
"Transmission",
"DateContactMedecin",
"DevenirIntervention",
"CotationClinique",
"CotationEconomique",
"CotationOrganisationnel",
"Conciliation",
"JustificatifIntervention"
]
#on creer une liste pour faire un for sur les nombres
nombre = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
# on se connecte à la base
conn = sqlite3.connect('déclaration.db')
cursor = conn.cursor()
# on va utiliser l'interface pour saisir et modifier les IP
# on va donc verifier si le numeroIP est saisie, dans la textbox, si ce n'est pas le cas on ajoute et on
# affiche le numero IP
# si c'est n'ai pas le cas on verifie que l'IP existe est on la met à jour
if len(self.NumIP.get_text()) == 0:
for i in IP:
cursor.execute(
"INSERT INTO Intervention(DateSaisie,Utilisateur,NomPatient,PrenomPatient,AgePatient,"
"UniteAgePatient,SexePatient,Poids,Probleme,Medicament1,CodeUCD1,ATC1,Medicament2,CodeUCD2,"
"ATC2,Service,DescriptionProbleme,Intervention,Prescripteur,Transmission,DateContactMedecin,"
"DevenirIntervention,CotationClinique,CotationEconomique,CotationOrganisationnel,Conciliation,"
"JustificatifIntervention) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", i)
id = cursor.lastrowid
message = "Féliciation vous avez sauvegarder votre IP sous le numero " + str(id)
self.NumIP.set_text(str(id))
Alerte.appelAffichageAlerte(message)
conn.commit()
conn.close()
else:
# on va tester voir si le numero de l'IP existe
cursor.execute("SELECT count(*) FROM Intervention WHERE id= ?", (int(self.NumIP.get_text()),))
IpExiste = cursor.fetchone()
if IpExiste[0] == 0:
Alerte.appelAffichageAlerte("L'IP n'existe pas")
conn.close()
else:
# on creer une boucle pour mettre à jour l'IP
for i in nombre:
sql = "UPDATE Intervention SET " + ColonneSQL[i] + "=? WHERE id=" + str(self.NumIP.get_text())
cursor.execute(sql, (IP[0][i],))
conn.commit()
conn.close()
def Lecture(self,widget):
"""
Cette fonction permet de lire la BDD et si , l'IP existe, mettre l'ensemble des données dans l'interface.
"""
if self.NumIP.get_text() is None or self.NumIP.get_text()=="":
self.effacerinterface(self)
else:
conn = sqlite3.connect('déclaration.db')
cursor = conn.cursor()
cursor.execute("SELECT count(*) FROM Intervention WHERE id= ?", (int(self.NumIP.get_text()),))
IpExiste = cursor.fetchone()
if IpExiste[0] == 1:
cursor.execute("SELECT * FROM Intervention WHERE id= ?",(int(self.NumIP.get_text()),))
ip_complete = cursor.fetchone()
cursor.execute("SELECT Libelle FROM Medoc WHERE id= ?",(int(ip_complete[10]),))
NomMedicament1 = cursor.fetchone()
if int(ip_complete[13])==0:
NomMedicament2=[""]
else:
cursor.execute("SELECT Libelle FROM Medoc WHERE id= ?",(int(ip_complete[13]),))
NomMedicament2 = cursor.fetchone()
conn.close()
self.DateIP.set_text(ip_complete[1])
self.Service.set_active(int(ip_complete[16])-1)
self.NomPatient.set_text(ip_complete[3])
self.PrenomPatient.set_text(ip_complete[4])
self.Age.set_text(str(ip_complete[5]))
self.UniteAge.set_active(ip_complete[6]-1)
self.Sexe.set_active(ip_complete[7] - 1)
self.Poids.set_text(ip_complete[8])
self.Probleme.set_active(ip_complete[9]-1)
self.builder.get_object("EntreMedoc1").set_text(NomMedicament1[0])
self.ATC1.set_active(ip_complete[12]-1)
self.builder.get_object("EntreMedoc2").set_text(NomMedicament2[0])
self.ATC2.set_active(ip_complete[15]-1)
self.ProblemeDescription.set_text(ip_complete[17])
self.Intervention.set_active(ip_complete[18]-1)
self.Prescripteur.set_active(ip_complete[19]-1)
self.Contact.set_active(ip_complete[20]-1)
self.DateMedecin.set_text(ip_complete[21])
self.Devenir.set_active(ip_complete[22]-1)
self.CotationClinique.set_active(ip_complete[23]-1)
self.CotationEconomique.set_active(ip_complete[24]-1)
self.CotationOrga.set_active(ip_complete[25]-1)
if ip_complete[26]==self.Conciliation.get_label():
pass
else:
self.Conciliation.activate()
self.RetourMedecin.set_text(ip_complete[27])
else:
self.effacerinterface(self)
def ChangementMedicament1(self,widget):
"""
Permet de changer le code ATC automatiquement quand on saisie un médicament dans la bare 1
"""
if self.builder.get_object("EntreMedoc1").get_text()=="":
pass
else:
conn = sqlite3.connect('déclaration.db')
cursor = conn.cursor()
SQL = "SELECT ClasseATC FROM Medoc WHERE Libelle= ?"
Val = self.builder.get_object("EntreMedoc1").get_text()
cursor.execute(SQL ,(Val,) )
ClassATC = cursor.fetchone()
if cursor.rowcount <0:
self.builder.get_object("EntreClasseATC1").set_text("")
else:
self.ATC1.set_active(ClassATC[0] - 1)
def ChangementMedicament2(self,widget):
"""
Permet de changer le code ATC automatiquement quand on saisie un médicament dans la bare 2
"""
if self.builder.get_object("EntreMedoc2").get_text()=="":
pass
else:
conn = sqlite3.connect('déclaration.db')
cursor = conn.cursor()
SQL = "SELECT ClasseATC FROM Medoc WHERE Libelle= ?"
Val = self.builder.get_object("EntreMedoc2").get_text()
cursor.execute(SQL ,(Val,) )
ClassATC = cursor.fetchone()
if cursor.rowcount<0:
self.builder.get_object("EntreClasseATC2").set_text("")
else:
self.ATC2.set_active(ClassATC[0] - 1)
def effacerinterface(self,widget):
dateBrut = datetime.datetime.now()
DateJour = FormatDate(dateBrut.day, dateBrut.month, dateBrut.year)
self.DateIP.set_text(DateJour)
self.builder.get_object("EntreService").set_text("")
self.NomPatient.set_text("")
self.PrenomPatient.set_text("")
self.Age.set_text("")
self.builder.get_object("EntreUA").set_text("")
self.builder.get_object("EntreSexe").set_text("")
self.Poids.set_text("")
self.builder.get_object("EntreProbleme").set_text("")
self.builder.get_object("EntreMedoc1").set_text("")
self.builder.get_object("EntreClasseATC1").set_text("")
self.builder.get_object("EntreMedoc2").set_text("")
self.builder.get_object("EntreClasseATC2").set_text("")
self.ProblemeDescription.set_text("")
self.builder.get_object("EntreIntervention").set_text("")
self.builder.get_object("EntreMedecin").set_text("")
self.builder.get_object("EntreContact").set_text("")
self.DateMedecin.set_text("")
self.builder.get_object("EntreDevenir").set_text("")
self.builder.get_object("EntreClinique").set_text("")
self.builder.get_object("EntreEconomique").set_text("")
self.builder.get_object("EntreOrga").set_text("")
if self.Conciliation.get_label() == "Oui":
self.Conciliation.activate()
def FermetureIP(self,widget):
Gtk.main_quit()
self.window.destroy()
def FormatDate(jour, mois, annee):
jour = str(jour)
mois = str(mois)
annee = str(annee)
if len(jour) < 2: jour = "0" + jour
if len(mois) < 2: mois = "0" + mois
return str(jour) + "/" + str(mois) + "/" + str(annee)
def appelAffichageAjoutIP(IDUtilisateurEnvoye):
global Idutilisateur
Idutilisateur = IDUtilisateurEnvoye
AffichageEcritureIP()
Gtk.main()
here the all project
Thank you for your futur answer
Hello I found the error
#on va creer l'autocomplete pour les medicament
self.liststoreMedoc = Gtk.ListStore(str)
for s in list(sum(self.ListeMedoc,())):
self.liststoreMedoc.append([s])
self.autocompletemedoc = Gtk.EntryCompletion()
self.autocompletemedoc.set_model(self.liststoreMedoc)
self.autocompletemedoc.set_text_column(0)
self.builder.get_object("EntreMedoc1").set_completion(self.autocompletemedoc)
self.builder.get_object("EntreMedoc2").set_completion(self.autocompletemedoc)
I used the same self.autocompletemedoc for the two entry.
I use the following algorithme in order to find the error :
1) removing the last function added
2) try the code
I correct the code with the folling
self.liststoreMedoc = Gtk.ListStore(str)
self.liststoreMedoc2 = Gtk.ListStore(str)
for s in list(sum(self.ListeMedoc,())):
self.liststoreMedoc.append([s])
self.liststoreMedoc2.append([s])
self.autocompletemedoc = Gtk.EntryCompletion()
self.autocompletemedoc2 = Gtk.EntryCompletion()
self.autocompletemedoc.set_model(self.liststoreMedoc)
self.autocompletemedo2c.set_model(self.liststoreMedoc2)
self.autocompletemedoc.set_text_column(0)
self.autocompletemedoc2.set_text_column(0)
self.builder.get_object("EntreMedoc1").set_completion(self.autocompletemedoc)
self.builder.get_object("EntreMedoc2").set_completion(self.autocompletemedoc2)
Now it's working and I can close my windows

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.

Indexes out of range, not finding the exact error

I'm essentially new to coding and I've been reading about Python. But I don't seem to find the error in my code. If you could help me with it, it would be great. Also any correction or observation is welcome.
I'm having this error:
Code cause error
if ((lista1[1] >= lista1[2]) and (lista1[2] >= 0)):
Error:
IndexError: list index out of range
My Code:
import math
import numpy as np
lista1=[1,3]
def von_mises(sigma_A, sigma_B, tao_XY):
print("Las unidades de los valores ingresados se encuentran en kpsi")
print("Ingresar el valor del esfuerzo en X:\n")
sigma_A = input() #Input regresa una cadena de caracteres, no valores numéricos
sigma_A = int(sigma_A)
print("Ingresar el valor del esfuerzo en Y:\n")
sigma_B = input()
sigma_B = int(sigma_B)
print("Ingresar el valor del esfuerzo cortante Tao:\n")
tao_XY = input()
tao_XY = int(tao_XY)
sigma_von = math.sqrt((pow(sigma_A, 2))-(sigma_A*sigma_B)+(pow(sigma_B, 2))+(3*(pow(tao_XY, 2))))
lista1 = np.array([sigma_von, sigma_A, sigma_B])
return lista1 #para simplificar el llamado de los valores que arroja esta función
def ED(res_ced, lista1):
print("Ingresar el valor de la resistencia a la cedencia:\n")
res_ced = input()
res_ced = int(res_ced)
n_ED = res_ced/lista1[0] #se invoca a la función de von mises para simplificar
print("El factor de seguridad ED es:")
print(n_ED)
def ECM(lista1, res_ced):
if ((lista1[1] >= lista1[2]) and (lista1[2] >= 0)):
n_ECM = res_ced/lista1[1]
elif ((lista1[1] >= 0) and (lista1[2] <= 0)):
n_ECM = res_ced/(lista1[1]-lista1[2])
else:
n_ECM = res_ced/(-lista1[2])
print("El factor de seguridad ECM es:")
print(n_ECM)
#MAIN
res_ced=0
tao_XY=0
sigma_A=0
sigma_B=0
ED(res_ced,von_mises(sigma_A, sigma_B, tao_XY))
ECM(lista1, res_ced)
In python, list indexing starts with 0.
It should work if you change your code to
if ((lista1[0] >= lista1[1]) and (lista1[1] >= 0))
It's because python indexing starts from zero, so:
...
def ECM(lista1, res_ced):
if ((lista1[0] >= lista1[1]) and (lista1[1] >= 0)):
n_ECM = res_ced/lista1[0]
elif ((lista1[0] >= 0) and (lista1[1] <= 0)):
n_ECM = res_ced/(lista1[0]-lista1[1])
else:
n_ECM = res_ced/(-lista1[1])
print("El factor de seguridad ECM es:")
print(n_ECM)
...
lista1 is:
[1,3]
it only contains to elements,so since:
------- -------
| 1 | | 3 |
------- -------
0 1

Python error when comparing strings

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

Categories

Resources