Replacing Consonants and Vowels in a String - Python/PySimpleGUI

80 Views Asked by At

Dears,

I want to write a function in Python, given a string, returns a new string in which the vowel will remain as it is and the consonants will be replaced with grec alphabet : α, β, γ, δ, ε, ...., Ω ω. And once there is a duplicate consanant, same letter will be used :

Let me clarify this by examples :

String "Better" :

1 - "B" 1st Consonant will be replaced by 1st letter in alphabet "α"
2 - "e" is **vowel** will be kept as it is "e"
3 - "t" 2nd Consonant will be replaced by 2nd letter in alphabet "β"
4 - "t" 2nd Consonant ( duplicate) will be replaced by 2nd letter in alphabet "β"
5 - "e" is vowel will be kept as it is "e"
6 - "r" 3rd Consonant will be replaced by 3rd letter in alphabet "γ"

So we'll end up with the following string : "αeββeγ"

Here's the code after Rouven's suggestions :

import PySimpleGUI as sg

a = "αβγ" # replace with the complete greek alphabet
s = "Better"
vovels = "AEIOUaeiou"
already_replaced = {}
new_string = ""
counter = 0

layout = [

[sg.Text('Word:', size=(15,1)), sg.Input(enable_events=True, key='WORD', 
 size=(25,1)),
 sg.Text('Result:', size=(15,1)), sg.Input(enable_events=True, 
 key='RESULT', size=(25,1))],
 ]

 window = sg.Window('MAIN',  layout, 
 finalize=True,element_justification='c')


 while True:

   event, values = window.read()
   #print(event, values)

   if event == sg.WIN_CLOSED or event == 'Exit':
       break

   elif event == 'WORD':

    for c in s:
        if c in vovels:
            new_string += c
        elif c in already_replaced.keys():
            new_string += already_replaced[c]
        else:
            new_string += a[counter]
            already_replaced[c] = a[counter]
            counter += 1
    print(new_string)
  window.close()

Thanks in advance

1

There are 1 best solutions below

7
hedg3hog On

This should work:

a = "αβγ" # replace with the complete greek alphabet
s = "Better"
vovels = "AEIOUaeiou"
already_replaced = {}
new_string = ""
counter = 0
for c in s:
     if c in vovels:
         new_string += c
     elif c in already_replaced.keys():
         new_string += already_replaced[c]
     else:
         new_string += a[counter]
         already_replaced[c] = a[counter]
         counter += 1