import re
text = input("Enter text: ")
text = text.lower()
len = len(text)
lenid = len - 1
def translate(text):
translation = ""
slocid = text.index("s")
for letter in text:
if (text[lenid] == "s") or (text[slocid 1] == " "):
translation = re.sub(r"s\b", lambda m: m.group().replace("s", "ς"), text)
if letter == "s":
translation = translation.replace("s", "σ")
if letter == "a":
translation = translation "α"
else:
translation = translation letter
return translation
print(translate(text))
I want to make a program where, when I enter a text, I get back the same text but
- all the
"s"
at the end of a word are replaced with"ς"
- if they're not at the end of the word, I want the
"s"
to be replaced with"σ"
. - If the letter is
"a"
I want it replaced with"α"
.
I'm trying to make a Greeklish to Greek translator and it just seems I messed up.
input: "as"
output: "aςs"
what I want: "ας"
input: "sa"
output: "sa"
what I want: "σα"
input: "sakas"
output: "σakaςs"
what I want: "σαkας"
CodePudding user response:
You currently translate the text character by character, but your regex and replace
work on the whole string so you can just apply them to the whole string instead.
def translate(text):
return re.sub(r"s\b", "ς", text)\
.replace("s", "σ")\
.replace("a", "α")
This will first sub your regex to replace ending 's' characters, then replaces the remaining 's' characters and then the 'a' characters.
CodePudding user response:
If you wanna understand the logic behind, the following code will help you understand how does it works.
def translate(text):
# checks 's' is present in 'text'
if 's' in text:
# checks if 's' appears at the end of 'text'
if text[-1] == 's':
# checks if 's' appears between 'tex'
if 's' in text[:-1]:
text = text.replace('s', 'σ')
# replace 's' with 'ς'
text = text[:-1] 'ς'
else:
# replace 's' with 'σ'
text = text.replace('s', 'σ')
# checks 'a' is present in 'text'
if 'a' in text:
# replace 'a' with 'α'
text = text.replace('a', 'α')
return text