I want to verify in Python if a word of an input exists in a vector

1

Here's the code I was trying:

  print("Prueba para determinar palabras")

  #El vector insultos con las palabras que deseo verificar
  claves=['hambre', 'comida']
  mensaje=[]

  msj = input("Digita una oracion: ")

  #Esto separará las palabras del input
  mensaje2 = msj.split()

  mensaje.append(mensaje2)

  print (mensaje)

  cont = 0
  print("")
  if mensaje[cont] in claves:
    print("Mañana te cocino")
    cont = cont + 1

  else:
    print("Ok")

   input("")
    
asked by Kemill 07.08.2018 в 15:51
source

2 answers

1

If you want to know if any of the words contained in claves is in the string just entered you must go through the list generated by str.split and go checking one by one each word:

print("Prueba para determinar palabras")
claves = ['hambre', 'comida']
msj = input("Digita una oracion: ")
mensaje = msj.split()

for palabra in mensaje:
    if palabra in claves:
        print("Mañana te cocino")
        break
else:  # Si el ciclo se ha completado (no se ha ejecutado break)
    print("Ok")

input()

Since I suppose you do not intend to count the number of times a forbidden word appears, it is a good idea to break the cycle at the moment when a match is found ( short circuiting ), for this use break .

Another way to do this is to use the built-in any next to a generator that also iterates over the list and performs the membership check with in . any returns True if at least one of the values of the iterable is evaluated as true.

On the other hand, if keys instead of a list is a set ( set ) the process will be considerably more efficient when using a hash table for the search, instead of having to go through the entire list claves complete every time you do palabra in claves :

print("Prueba para determinar palabras")
claves = {'hambre', 'comida'}
msj = input("Digita una oracion: ")
mensaje = msj.split()

if any(palabra in claves for palabra in mensaje):
    print("Mañana te cocino")
else:
    print("Ok")

input()
    
answered by 07.08.2018 в 16:45
0

The fastest way would be using

 if any(word in msj for word in claves):

according to your code, you get what you write and convert it into an arrangement to get the words and find the match in the ['hambre', 'comida'] array.

As an example if I write hola soy Kemill y tengo hambre , I would get the words and determine that one of the words is in the array:

[['hola', 'soy', 'Kemill', 'y', 'tengo', 'hambre']]

and in this way print:

Manana te cocino

example in your code:

print("Prueba para determinar palabras")

#El vector insultos con las palabras que deseo verificar
claves=['hambre', 'comida']
mensaje=[]

msj = input("Digita una oracion: ")

#Esto separará las palabras del input
mensaje2 = msj.split()

mensaje.append(mensaje2)

print (mensaje)

if any(word in msj for word in claves):
    print("Manana te cocino")    
else:
    print("Ok")  
    
answered by 07.08.2018 в 16:46