如果字符串仅包含"-"或"."



我正在编写一个小函数,检查输入的字符串是否为莫尔斯电码。函数应该是这样的"If "-"或"."仅在Inputted_string中:"但我似乎找不到一种方法来做Python3上唯一的一点。目前我实现这个的方式是非常混乱,不是很python

if "-" in message:
    # message might be morse code so check even more
        if "." in message:
            # Message IS morse code so return true
            return True
        else:
            # TODO you can use a REGEX for the below things
            if '--' in message:
                # if the messsage contains only hyphens, then check to see if
                # message contans hyphen only morse code by checking all hyphen
                # only morse code against message
                return True
            elif '-----' in message:
                # if message contains 0 in morse code, return True
                return True
    if "." in message:
        # message might contain morse code
        if "-" in message:
            # message IS morse code.
            return True
        else:
            # check to see if message is dots only morse code
            # TODO you can use a REGEX for the below things
            if ".." in message:
                # message IS Morse Code
                return True
            elif "..." in message:
                # message IS Morse Code
                return True
            elif "....":
            # message IS Morse Code
                return True
        # if dots or dash not in message, return none
        return("Message has no hyphens or full stops")
当我粘贴时,

的格式有点偏离,但这是一般的要点。当它检查,看看如果消息是"----"或".."等,这是因为一些莫尔斯电码字母只是那些字符,但我相信有一个更容易的方法去解决这个!

def is_morse(message):
    allowed = {".", "-", " "}
    return allowed.issuperset(message)

但是因为消息包含了所有的字符并不意味着它是有效的。你需要检查每个字符是否有效你可以使用字典将字母映射到莫尔斯,你还需要一些明确的格式,即字母之间有一个空格,单词之间有两个或更多的空格:

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

msg = ".... . .-.. .-.. -----  .-- --- .-. .-.. -.."
def is_morse(message):
    spl = message.split(" ")
    return  all(m in morse for m in spl)
if is_morse(msg):
    print("".join([morse[ch] for ch in msg.split(" ")]))

可以将其解析为获得所有变体的单个字符串,只是需要更多的工作。

如果你想用另一种方式,那么你只需要反向映射:

to_morse = {v: k for k, v in morse.items()}
def can_morse(msg):
    return all(ch in to_morse for ch in msg.upper())

msg = "Hello  World"
if can_morse(msg):
    print(" ".join([to_morse[ch] for ch in msg.upper()]))

我选择额外的空格来分隔单词,你可以选择任何你喜欢的只要确保将字符添加到字典映射然后添加到空格或任何你想要的分隔单词的。

您可以使用any():

def is_morse(message):
    return bool(message) and not any(ch not in '.- ' for ch in message)

bool(message)位也拒绝零长度的消息

检查message的每个元素是否在正确的字母表中:

if all(c in ['-', '.'] for c in message):

或将消息缩减为一个集合:

if set(message) <= set(['.', '-'])

或使用正则表达式:

if re.match('[-.]*$', message):

使用一个简单的正则表达式-

import re
def is_morse(message):
    return True if bool(re.match(r'^[.-]+$', message)) else False

这可能也比遍历message中的每个字符要快。

我想大多数python会在这里使用列表推导式。这检查字符串是否完全由out - and组成。人物:

s = '---...---'
ismorse = all(c in ('-','.') for c in s)

这能满足你的需求吗?

for char in message:
    if char not in '.-':
        return False
return True

最新更新