我想编写一个函数,该函数将使用字符串并将单词转换为Pyg Latin。这意味着:
我找到了一个可以将其转换成必须的格式的程序,但是我不确定如何对其进行编辑,以便它可以返回所需的结果。
def pyg_latin(fir_str):
pyg = 'ay'
pyg_input = fir_str
if len(pyg_input) > 0 and pyg_input.isalpha():
lwr_input = pyg_input.lower()
lst = lwr_input.split()
latin = []
for item in lst:
frst = item[0]
if frst in 'aeiou':
item = item + pyg
else:
item = item[1:] + frst + pyg
latin.append(item)
return ' '.join(latin)
因此,这就是我的代码执行的结果:
pyg_latin('fish')
#it returns
'ishfay'
我希望它返回的内容没有太大不同,但是我不知道如何添加它
pyg_latin('fish')
#it returns
'ish-fay'
考虑一下字符串应该是什么样子。
文本块,后跟连字符,后跟第一个字母(如果不是元音),后跟“ ay”。
您可以使用python字符串格式设置,也可以将字符串添加在一起:
Item[1:] + “-“ + frst + pyg
还值得学习数组切片的工作原理以及字符串是可以通过符号访问的数组。以下代码似乎适用于您的测试用例。您应该重构它并了解每一行的功能。使解决方案更加健壮,但要添加测试场景,例如“ 1st”或带标点的句子。您还可以构建一个函数,该函数创建猪的拉丁字符串并返回它,然后重构代码以利用它。
def pg(w):
w = w.lower()
string = ''
if w[0] not in 'aeiou':
if w[1] not in 'aeiou':
string = w[2:] + "-" + w[:2] + "ay"
return string
else:
string = w[1:] + "-" + w[0] + "ay"
return string
else:
string = w + "-" + "way"
return string
words = ['fish', 'frish', 'ish', 'tis but a scratch']
for word in words:
# Type check the incoming object and raise an error if it is not a list or string
# This allows handling both 'fish' and 'tis but a scratch' but not 5.
if isinstance(word, str):
new_phrase = ''
if ' ' in word:
for w in word.split(' '):
new_phrase += (pg(w)) + ' '
else:
new_phrase = pg(word)
print(new_phrase)
# Raise a Type exception if the object being processed is not a string
else:
raise TypeError
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句