Buscador de palabras que empiecen por una letra [ESP-ENG] | Python

¿Qué tal? He aquí estoy de vuelta con otro ejercicio de programación en Python. Para esta ocasión, añadí validaciones, de modo que está un poco más completo.

El enunciado dice lo siguiente: Crear un programa que solicite el ingreso de un texto y luego de una palabra. Luego muestre, ordenadamente, en orden alfabético, todas las palabras que empiecen por esa letra.

How are you doing? Here I am back with another Python programming exercise. For this one, I added validations, so it's a bit more complete.

The statement reads as follows: Create a program that prompts for the input of a text and then a word. Then display, in alphabetical order, all the words beginning with that letter.


Portada post programacion, tech.gif

Education separador png.png

Para empezar usé dos variables booleanas para controlar el bucle while de la validación y el condicional if-else, el primero, es decir, el más grande está controlado por "letter_pass", este aparece al principio y en otro bucle más adelante que es donde encontrarán la relación más cercana a su nombre, pues es donde se ingresa la letra.

Pero, antes de llegar allá, dentro del primer bucle se pide el texto a analizar y se guarda en la variable "texto". Luego se transforma en minúsculas para facilitar la búsqueda, posteriormente se usa la lista llamada "lista_palabras", para llenarla con cada palabra o conjunto de letras aleatorias separadas por un espacio " ". Esto a través de la función "split".

Posteriormente, con un bucle for se itera en la lista antes creada para revisar si cada una de las palabras ingresadas está conformada de letras del alfabeto o se ingresó algún caracter no deseado.

Para ello empleo la variable "text_pass" como variable booleana que contralo si el bucle siguiente se ejecutará o no. Si no se cumple la condición se despliega un mensaje de error y se procede a repetir el principio del bucle, es decir, pedir de nuevo el texto para filtrarlo.

Si se cumple la condición, se entra a otro bucle para pedir la letra, en este caso se valida que sea alfabético el caracter pero también que sea uno solo y no una frase o palabra entera, pues se debe cumplir el enunciado. Además, usé una variable para contar el número de coincidencias más adelante y ordené la lista de palabras para cumplir la otra parte del enunciado.

Si la palabra pasa el filtro se entra a otro bucle for en el que, si se encuentra la palabra, se imprime en pantalla y se aumenta el contador de coincidencias. Dado que la lista ya estaba ordenada alfabéticamente y las coincidencias se van revisando una a una en la lista, salen ordenadas correctamente.

Una vez terminan de imprimirse todas, se procede a desplegar un mensaje que dice el número de coincidencias halladas y se finaliza el programa.

To begin with I used two boolean variables to control the while loop of the validation and the conditional if-else, the first one, that is to say, the biggest one is controlled by "letter_pass", this appears at the beginning and in another loop later that is where you will find the closest relationship to its name, because it is where the letter is entered.

But, before getting there, inside the first loop the text to be analyzed is requested and stored in the variable "text". Then it is transformed into lowercase to facilitate the search, then the list called "word_list" is used to fill it with each word or set of random letters separated by a space " ". This is done through the "split" function.

Subsequently, with a for loop iterates in the list created before to check if each of the words entered is made up of letters of the alphabet or any unwanted character was entered.

To do this I use the variable "text_pass" as a boolean variable that controls whether the following loop will be executed or not. If the condition is not met, an error message is displayed and the beginning of the loop is repeated, that is, the text is requested again to filter it.

If the condition is met, another loop is entered to ask for the letter, in this case it is validated that the character is alphabetic but also that it is a single character and not a phrase or a whole word, because the statement must be met. In addition, I used a variable to count the number of matches later and ordered the list of words to fulfill the other part of the statement.

If the word passes the filter another for loop is entered in which, if the word is found, it is printed on the screen and the match counter is incremented. Since the list was already sorted alphabetically and the matches are checked one by one in the list, they are correctly sorted.

Once all the matches have been printed, a message is displayed indicating the number of matches found and the program is finished.

Education separador png.png

image.png

Education separador png.png

Y bueno, en cuanto a ejecución, no está nada mal. Tan solo agregaría que se le puede añadir una excepción para que deje pasar comas y puntos, de modo que no sea tan limitada esa parte y el usuario tenga un poco más de libertad. Sumado a esto, dar algunas excepciones a la parte numérica también podría ser prudente, para los casos de fechas o número de años y edades.

Pero bueno, eso ha sido todo por ahora. Espero que les haya agradado y si tienen algún conocido al que le pueda ser de ayuda este contenido, no duden en compartirlo. Saludos y muchas bendiciones.

And well, in terms of execution, it is not bad at all. I would only add that you can add an exception to let commas and periods pass, so that it is not so limited that part and the user has a little more freedom. In addition to this, giving some exceptions to the numerical part could also be prudent, for the cases of dates or number of years and ages.

But well, that's all for now. I hope you liked it and if you have any acquaintance that could find this content helpful, do not hesitate to share it. Greetings and many blessings.

Education separador png.png

image.png

Education separador png.png


Redes actualizada.gif


Puedes seguirme por acá si lo deseas:
You can follow me here if you want:

Cuenta secundaria
(Dibujos, edición y juegos) | Secondary account (Drawings, editing and games)



0
0
0.000
6 comments
avatar
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
 

0
0
0.000
avatar

Congratulations @gabrielr29! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

You distributed more than 14000 upvotes.
Your next target is to reach 15000 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Check out our last posts:

Women's World Cup Contest - Round of 16 - Recap of Day 4
Women's World Cup Contest - Round of 16 - Recap of Day 3
Women's World Cup Contest - Round of 16 - Recap of Day 2
0
0
0.000