<p>我正在写一个小函数来检查输入的字符串是否是莫尔斯电码。
该函数应该执行以下操作:
如果“-”或“.”仅在输入的字符串中:
但我似乎找不到一种方法来做Python3上唯一的一点。
目前我实现这个的方法是<strong>非常</strong>凌乱而不是非常python</p>
<pre><code>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")
</code></pre>
<p>当我粘贴的时候,格式有点偏差,但这是基本要点。
当它检查信息是否是“---”或“.”等时,这是因为有些摩尔斯电码字母只是这些字符,但我相信有一个更简单的方法来绕过这个问题!在</p>
<p>您可以使用<code>any()</code>:</p>
<pre><code>def is_morse(message):
return bool(message) and not any(ch not in '.- ' for ch in message)
</code></pre>
<p><code>bool(message)</code>位也拒绝零长度的消息。在</p>