在python中为莫尔斯字母翻译添加空格



你好,我写这段代码是为了用莫尔斯字母表翻译用户输入并将其写入文件,但我有一个问题:每个字母之间没有空格。提前谢谢你,如果需要的话,我可以重新解释这个问题。

import re

def txt_2_morse(msg):

morse = {
'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.',
'F':'..-.', 'G':'--.', 'H':'....', 'I':'..', 'J':'.---',
'K':'-.-', 'L':'.-..', 'M':'--', 'N':'-.', 'O':'---',
'P':'.--.', 'Q':'--.-', 'R':'.-.', 'S':'...', 'T':'-',
'U':'..-', 'V':'...-', 'W':'.--', 'X':'-..-', 'Y':'-.--',
'Z':'--..', '1':'.----', '2':'..---', '3':'...--', '4':'....-',
'5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.',
'0':'-----', ' ':'/'}

return "".join([morse.get(c.upper(), ' ') for c in msg])


while True:
user_input = input('Input your hidden message!')
regex_matcher= re.compile("/[a-z]+[A-Z]+[0-9]/g")
if (regex_matcher.search(user_input)  == False ):
user_input
else: 
f = open("myfile.txt", "w")
f.write(txt_2_morse(user_input + "n"))
f.close()
break

如何在每个字母/数字写入文件后添加空格

因为生成文件主体的代码是

"".join([morse.get(c.upper(), ' ') for c in msg])

你所需要做的就是使用一个空格而不是空字符串

" ".join([morse.get(c.upper(), ' ') for c in msg])

最新更新