所以我想做的是一个程序它可以编码和解码“Löffelsprache”这是一种德国有趣的编码
其工作原理如下:每个元音被替换为“元音本身”+短+“再次元音”默认短为“lew”;例如:hello > helewellolewo
我在代码中实现了这一点,但它很混乱,不是最优雅的解决方案。
也有规则,“耳朵”不会翻译“elewealewar”,而只是“elewear”。
所以如果后面有第二个元音,它会被忽略。
为了更好地理解,我发现这个在线生成器使用“b”作为缩写:https://de.toolpage.org/tool/bsprache
验证码:
# Get user input
inputtextraw = input("What to en/decrypt?\n").lower()
# set the message to be translated (inputtext)
inputtext = inputtextraw
# set the short
shortraw = "lew"
# Set a placeholder so the following replace functions don't replace part of the previously placed short
short_placeholder = "@"
# Find out if it's already encoded or needs to be encoded
if "a" + shortraw + "a" in inputtext or "e" + shortraw + "e" in inputtext or "i" + shortraw + "i" in inputtext or "o" + shortraw + "o" in inputtext or "u" + shortraw + "u" in inputtext:
# DECODE
try:
# Replace all shorts with the placeholder
inputtext = inputtext.replace(shortraw, short_placeholder)
# Decode
inputtext = inputtext.replace("e" + short_placeholder + "e", "e")
inputtext = inputtext.replace("a" + short_placeholder + "a", "a")
inputtext = inputtext.replace("i" + short_placeholder + "i", "i")
inputtext = inputtext.replace("o" + short_placeholder + "o", "o")
inputtext = inputtext.replace("u" + short_placeholder + "u", "u")
# Save result
result = inputtext
except:
print("error")
print('\n"' + inputtextraw + '" means:\n' + result + '\n')
else:
# ENCODE
try:
# Encode to vowel + placeholder + vowel
inputtext = inputtext.replace("e", "e" + short_placeholder + "e")
inputtext = inputtext.replace("a", "a" + short_placeholder + "a")
inputtext = inputtext.replace("i", "i" + short_placeholder + "i")
inputtext = inputtext.replace("o", "o" + short_placeholder + "o")
inputtext = inputtext.replace("u", "u" + short_placeholder + "u")
# replace the placeholder with the actual short
result = inputtext.replace(short_placeholder, shortraw)
except:
print("error")
print('\n"' + inputtextraw + '" in ' + shortraw + ' code is:\n' + result + '\n')
2条答案
按热度按时间hi3rlvi21#
不要使用
replace()
进行编码,只需迭代字符串并检查每个字符是否在字符/元音列表中。因为你想跳过第二个元音的编码,你必须在处理下一个字符之前检查最后一个字符是否被编码:
最后,你必须将生成的结果
join()
设置为一个新的字符串。示例
nqwrtyyt2#
我发现一个简单的正则表达式是优雅的。
捕获一个后面没有另一个元音的元音,然后将捕获的元音替换为它本身,
lew
,然后再替换它本身。代码:(Demo)