Modificador de oraciones (Vocales a mayúsculas) [ESP-ENG] | Python

avatar
(Edited)

Saludos, he aquí estoy de vuelta con más sobre mi progreso de aprendizaje de este lenguaje de programación conocido como Python. Esta vez el programa no tiene tantos detalles como el anterior, pues parte de un enunciado más simple. Es el siguiente:

"Dada una oración escrita toda en minúscula, convierta cada vocal existente en esta por su respectiva mayúscula".

Dado que el anterior fue un Mini-sistema de registro de deportistas (usando archivos), podría llegar a sentirse cierto bajón de nivel, pero lo cierto es que esa fue una asignación evaluada, mientras que este es un enunciado que forma parte de un listado de ejercicios de práctica. Por ello la diferencia marcada en complejidad.

Greetings, here I am back with more about my progress in learning this programming language known as Python. This time the program does not have as many details as the previous one, because it starts from a simpler statement. It is as follows:

"Given a sentence written all in lowercase, convert each existing vowel in this one by its respective uppercase".

Since the previous one was a Mini-athlete-registration-system (using files), you might feel some downgrading, but the truth is that this was an evaluated assignment, while this is a statement that is part of a list of practice exercises. Hence the marked difference in complexity.


Portada post programacion, tech (4).gif

Education separador png.png

Para comenzar importé la librería os y re, esto porque más adelante usaría la función os.system("cls"), para limpiar la consola y luego re.fullmatch() para filtrar correctamente la oración que el usuario ingresara por teclado.

El algoritmo para cumplir con el requerimiento principal se llama "vocals_upper" y tiene como parámetro a "txt", que será la oración a modificar. En esa función se itera en el texto recibido, de modo que si se cumple la condición de que un caracter sea una vocal, entonces esta se pasará de minúsculas a mayúsculas con la función upper(), seguidamente, se añadirá a otra cadena llamada "new_txt", si no es igual a una vocal igual se añadirá a la cadena antes mencionada pero sin la aplicación de upper(), pues la idea es copiar la cadena original, pero pasando a mayúsculas las vocales para cumplir con el requisito del enunciado. Al terminar se retorna la cadena "new_txt" que posee la cadena modificada en las vocales.

To begin with, I imported the os and re libraries, because later I would use the os.system("cls") function to clean the console and then re.fullmatch() to correctly filter the sentence that the user would enter by keyboard.

The algorithm to fulfill the main requirement is called "vocals_upper" and has "txt" as parameter, which will be the sentence to modify. In this function iterates in the received text, so that if the condition that a character is a vowel is met, then this will be changed from lowercase to uppercase with the upper() function, then, it will be added to another string called "new_txt", if it is not equal to a vowel it will be added to the aforementioned string but without the application of upper(), because the idea is to copy the original string, but changing the vowels to uppercase to meet the requirement of the statement. At the end, the string "new_txt" is returned, which has the modified string in the vowels.

Education separador png.png

image.png

Education separador png.png

Continúa la función "menu()", que es tal y como dice su nombre el menú del programa, pues pide el texto a modificar, lo filtra, lo muestra (de haberse filtrado correctamente), y posteriormente pregunta si se desea seguir modificando texto.

En esta función hay 2 variables booleanas, ambas para controlar su respectivo bucle while, el primero que sería el más grande depende de "val", que rompe el bucle cuando el usuario dice que no quiere seguir modificando texto. Y la segunda, "val2", pasa su estado a "falso", en ambos casos, pero vuelve a ser "True" cuando se repite el bucle principal, pues "val2", controla precisamente que se salga del apartado de ¿Quieres modificar más texto? Al decir que sí, se rompe ese bucle pero la variable vuelve a ser True al comienzo, de modo que se asegure que el bucle (Y/N) pueda volver a ejecutarse en la nueva vuelta.

En cuanto a la validación de lo que pasa el usuario por teclado, usé la función re.fullmatch(), esto lo explique un poco en un comentario en el código, pero puedes clicar acá para saber un poco más sobre la librería. Usé esa función y no "isalpha" porque tenía problemas respecto a los espacios. Isalpha los contaba como caracteres inválidos. Esto no sería un problema un poco menos grave si fuesen solo palabras, pero ante la existencia de oraciones, la cosa cambia un poco. Esa línea de código la conseguí en una discusión en stackoverflow respecto, precisamente a la validación de texto.

Ya en cuanto a su funcionamiento, pues no está nada mal, aunque para fines prácticos no tiene mucha utilidad a menos que quieras caricaturizar opiniones de personas en internet con la clásica jugada inmadura de repetir los argumentos contrarios y escribirlo dE EstA fOrmA.

The function "menu()" continues, which is, as its name says, the menu of the program, because it asks for the text to modify, filters it, shows it (if it has been filtered correctly), and later asks if it is desired to continue modifying text.

In this function there are 2 boolean variables, both to control their respective while loop, the first one that would be the biggest depends on "val", which breaks the loop when the user says that he does not want to continue modifying text. And the second one, "val2", passes its state to "false", in both cases, but returns to "True" when the main loop is repeated, because "val2", controls precisely that it leaves the section of Do you want to modify more text? By saying yes, this loop is broken but the variable returns to True at the beginning, so as to ensure that the loop (AND/N) can be executed again in the new round.

As for the validation of what the user passes by keyboard, I used the re.fullmatch() function, I explained this a bit in a comment in the code, but you can click here to know a bit more about the library. I used that function and not "isalpha" because I had problems with spaces. Isalpha counted them as invalid characters. This would be a little less of a problem if they were just words, but with sentences, things change a bit. I got that line of code in a stackoverflow discussion about text validation.

As for how it works, it is not bad, although for practical purposes it is not very useful unless you want to caricature opinions of people on the Internet with the classic immature move of repeating the opposing arguments and writing it iN thIs wAy.

Education separador png.png

image.png

Education separador png.png

Eso ha sido todo por hoy, otro día, otro pequeño ejercicio para ir mejorando en este mundo del código, del crear para optimizar, para mejorar... ¡Para avanzar!

Y como ya tengo por costumbre, te digo que, si andas buscando un buen curso de este lenguaje conocido como Python, en lo personal te recomiendo este: Clica aquí.

That's all for today, another day, another small exercise to improve in this world of coding, of creating to optimize, to improve... To move forward!

And as I am used to, I tell you that, if you are looking for a good course of this language known as Python, I personally recommend this one: Click here

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
17 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

Tu publicacion ha sido votada por el Trail de CAPYBARAEXCHANGE por contenido excepcional y formar parte de nuestra comunidad de usuarios activos.

Unete a nuestro canal de discord en dónde podrás conocer mas acerca de nuestras operaciones y servicios. registrate ingresando en capybaraexchange para disfrutar del servicio

Si quieres formar parte de nuestro trail de curación, ingresa a HIVEVOTE, haciendo clic en la imagen del capybara aristocratico. Capybaraexchange tu casa de cambio, rapida, confiable y segura



0
0
0.000
avatar

Congratulations your publication has been chosen among the best of the day.

KEEP CREATING GOOD CONTENT.

image.png

0
0
0.000
avatar

¡Enhorabuena!


Has recibido el voto de PROYECTO CHESS BROTHERS

✅ Has hecho un buen trabajo, por lo cual tu publicación ha sido valorada y ha recibido el apoyo de parte de CHESS BROTHERS ♔ 💪


♟ Te invitamos a usar nuestra etiqueta #chessbrothers y a que aprendas más sobre nosotros.

♟♟ También puedes contactarnos en nuestro servidor de Discord y promocionar allí tus publicaciones.

♟♟♟ Considera unirte a nuestro trail de curación para que trabajemos en equipo y recibas recompensas automáticamente.

♞♟ Echa un vistazo a nuestra cuenta @chessbrotherspro para que te informes sobre el proceso de curación llevado a diario por nuestro equipo.


🏅 Si quieres obtener ganancias con tu delegacion de HP y apoyar a nuestro proyecto, te invitamos a unirte al plan Master Investor. Aquí puedes aprender cómo hacerlo.


Cordialmente

El equipo de CHESS BROTHERS

0
0
0.000
avatar

¡Gracias, amantes del ajedrez! Mucho éxito en su proyecto

0
0
0.000
avatar

¡Felicitaciones!



Estás participando para optar a la mención especial de nuestra COMUNIDAD (Recompensa de 1 Hive), también has recibido 1 ENTROKEN.

1. Invierte en el PROYECTO ENTROPÍA y recibe ganancias semanalmente. Entra aquí para más información.

2. Contáctanos en Discord: https://discord.gg/hkCjFeb

3. Suscríbete a nuestra COMUNIDAD, apoya al trail de @Entropia y así podrás ganar recompensas de curación de forma automática. Entra aquí para más información sobre nuestro trail.

4. Creación de cuentas nuevas de Hive aquí.

5. Visita nuestro canal de Youtube.

Atentamente

El equipo de curación del PROYECTO ENTROPÍA

0
0
0.000