python - 在Python中的莫尔斯字母翻译中添加空格

标签 python

您好,我编写此代码是为了将用户输入翻译为莫尔斯字母并将其写入文件中,但我有 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/

相关文章:

python - 将图像加载到 Dask Dataframe 中

python - 如何在django中生成临时文件然后销毁

python - 尝试渲染条形码图像,但对象不可调用?

python : PortAudio + Opus encoding/decoding

python - 使用 allauth 登录时生成 jwt

python - C++ 嵌入式 Python PyBytes_AsString 导致 DLL 崩溃

python - 我可以在 Django 中使用订购方法吗?

Python 类属性装饰器不起作用

python - ValueError : Buffer dtype mismatch, 预期 'double' 但得到 'float'

python - 具有退出和重新启动循环的计算器程序