首页 > 解决方案 > 需要帮助将字符串翻译成 pyg latin

问题描述

我想编写一个函数,它将接受一个字符串并将单词转换为 Pyg 拉丁语。这意味着:

  1. 如果单词以元音开头,则在末尾添加“-way”。示例:“ant”变成“ant-way”。
  2. 如果单词以辅音簇开头,则将该簇移到末尾并添加“ay”。示例:“pant”变成“ant-pay”。我搜索了许多帖子和网站,但没有一个以相同的方式或我想要的方式进行。我必须在测试中测试这些功能,我有 4 个测试用例。一个是'fish',它应该返回'ish-fray',第二个是'fish',它应该返回'ish-fray',第三个是'ish',它应该返回'ish-way',最后一个是'tis但划痕',它应该返回'is-tay ut-bay a-way atch-scray'

我找到了一个程序,可以将它翻译成它必须是的,但我不确定如何编辑它,以便它可以返回我正在寻找的结果。

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'

标签: python

解决方案


想想字符串应该是什么样子。

文本块,后跟连字符,然后是第一个字母(如果它不是元音),然后是“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

推荐阅读