【问题标题】:Is there a way to include a space when splitting a string?有没有办法在拆分字符串时包含空格?
【发布时间】:2020-03-22 16:49:37
【问题描述】:

(感谢CoryKramer对帖子查询的代码:morse code to english python3

我正在编写一个莫尔斯电码程序。它适用于字符串到摩尔斯。在制作 morse-to-string 时,它会正确翻译 morse,但会忽略我的输出所需的空格。

这是我的代码:

def coder(text, to_morse=True):
    morse_key = {'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': '--..',

            '0': '-----',  '1': '.----',  '2': '..---',
            '3': '...--',  '4': '....-',  '5': '.....',
            '6': '-....',  '7': '--...',  '8': '---..',
            '9': '----.', ' ': ' '
            }

    key_reversed = {value: key for key, value in morse_key.items()}
    if to_morse:
        return ' '.join(morse_key.get(i.upper()) for i in text)
    else:
        x = ''.join([key_reversed.get(i) for i in text.split() for i in (i, ' ')][:-1])
        return str(x)

例如,如果我这样做:

coder('-.. .- - .-   ... -.-. .. . -. -.-. .', False)

它输出:

'D A T A S C I E N C E'

但是,我想要的输出是:

'DATA SCIENCE'

我应该如何在包含空格的同时实现split() 函数?

【问题讨论】:

标签: python string split


【解决方案1】:

else下的部分改为:

text = text.replace(' ', ',').replace(',,,', ', ,')
return ''.join(key_reversed.get(i) for i in text.split(','))

【讨论】:

    【解决方案2】:

    在你的 else 块中使用它

    else:
        words = text.split('   ') # split on 3 spaces
        x =[]
        for word in words:
            x.append(''.join([key_reversed.get(i) for i in word.split()]))
        return ' '.join(x)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-11
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多