您好,我编写此代码是为了将用户输入翻译为莫尔斯字母并将其写入文件中,但我有 1 个问题:每个字母之间没有空格。提前谢谢您,我可以重新解释如果需要的话,解决问题。
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
最佳答案
How can i add space after each letter/number after its written in the file
因为生成文件正文的代码是
"".join([morse.get(c.upper(), ' ') for c in msg])
您需要做的就是使用空格而不是空字符串
" ".join([morse.get(c.upper(), ' ') for c in msg])
关于python - 在Python中的莫尔斯字母翻译中添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70233166/