我一直试图让自己更具挑战性,但我无法找到实现这一目标的方法。所以我想知道是否可以分隔没有空格的单词betweenThemLikeThisJustInASingleString
这是我的代码:
def translate_morse(string):
morse_a = {
'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:'-----'}
translated = ""
for i in string.split(' '):
for key, value in morse_a.iteritems():
if i == value:
translated += key
print translated
print """
###################################
# #
# Morse Alphabet Translator #
# Author: Blackwolf #
# Date: 2016-29-05 #
# #
###################################
# #
# USAGE: #
# After each morse letter you #
# will need to seperate (space) #
# each letter #
###################################
"""
finished = False
while finished != True:
translate_morse(raw_input("Enter morse: "))
ask_ifFinished = raw_input('Are you done? (Y/N): ').lower()
if ask_ifFinished == 'y':
finished = True
答案 0 :(得分:5)
如果要在每个大写字母前插入一个空格:
import re
string = 'betweenThemLikeThisJustInASingleString'
print(re.sub('([A-Z])', r' \1', string))
输出:
between Them Like This Just In A Single String
没有完美的解决方案来分割未标记边界的单词。计算机如何判断singlestring
应该分为single string
而不是sing lest ring
(如果您不知道,lest
是一个英文单词)?有一些启发式方法可以用来做出不错的猜测,但它们很复杂且有限。您也可以列出所有可能的解决方案,但在您的级别上也很难。
答案 1 :(得分:4)
stackoverflow上的第一篇文章:)
正在研究如何解决其他问题,并认为我会分享它。
<强>要求强>
def spacer(str):
sentence = [] # create empty list
sentence.append(str[0]) # put first letter in list. First letter doesn't need a space.
for char in str[1::]: # begin iteration after first letter
if char.islower():
sentence.append(char) # if character is lower add to list
elif char.isupper():
sentence.append( " ") # if character is upper add a space to list
sentence.append(char) # then add the upper case character to list
result = ''.join(sentence) # use () join to convert the list to a string
return result # return end result
RUN IT
string='betweenThemLikeThisJustInASingleString'
spacer(string)
<强>输出强>
他们之间只是在一个字符串中的'