我创建了下面的函数来将罗马数字转换为单词形式。它按预期工作。如果建筑物/字符串以I-X中的罗马数字结尾,则会将其转换为单词。我知道有一个洞(如果罗马数字不是最后一个字的话)。我想不出如何实现这一点。想法
另外,我对Python还很陌生,所以我很好奇是否有必要清理代码。我觉得它很笨重
def replace_roman_numerals(string):
if len(string.split()) > 1: # if the community name has more than one word, split the words, else return community as is
first, *middle, last = string.split()
else:
first = ""
middle = ""
last = ""
w = string.split() # splits the community name into words
lw = w[len(w)-1] # returns the last word in the community
# convert RN into a word if the last word in the community is a RN and remove excessive blanks and characters from the middle variable
if lw in ("I", "1"): return " ".join((first + " " + str(middle)[1:-1].replace("'","").replace(",","") + " One").split())
elif lw in ("II", "2"): return " ".join((first + " " + str(middle)[1:-1].replace("'","").replace(",","") + " Two").split())
elif lw in ("III", "3"): return " ".join((first + " " + str(middle)[1:-1].replace("'","").replace(",","") + " Three").split())
elif lw in ("IV", "4"): return " ".join((first + " " + str(middle)[1:-1].replace("'","").replace(",","") + " Four").split())
elif lw in ("V", "5"): return " ".join((first + " " + str(middle)[1:-1].replace("'","").replace(",","") + " Five").split())
elif lw in ("VI", "6"): return " ".join((first + " " + str(middle)[1:-1].replace("'","").replace(",","") + " Six").split())
elif lw in ("VII", "7"): return " ".join((first + " " + str(middle)[1:-1].replace("'","").replace(",","") + " Seven").split())
elif lw in ("VIII", "8"): return " ".join((first + " " + str(middle)[1:-1].replace("'","").replace(",","") + " Eight").split())
elif lw in ("IX", "9"): return " ".join((first + " " + str(middle)[1:-1].replace("'","").replace(",","") + " Nine").split())
elif lw in ("X", "10"): return " ".join((first + " " + str(middle)[1:-1].replace("'","").replace(",","") + " Ten").split())
else: return " ".join((first + " " + str(middle)[1:-1].replace("'","").replace(",","") + " " + lw).split())
投入:
s = "Park III"
s = replace_roman_numerals(s)
print (s)
s = "American Tower - Bldg IV"
print (replace_roman_numerals(s))
s = "Estancia"
print (replace_roman_numerals(s))
s = "Park Place 9"
print (replace_roman_numerals(s))
产出是:
Park Three
American Tower - Bldg Four
Estancia
Park Place Nine
这将是一种更像python的方法:
产出:
相关问题 更多 >
编程相关推荐