Pig_Latin转换器和for循环

时间:2019-06-18 05:14:44

标签: python python-3.x

猪拉丁语翻译器基本上是许多项目的入门代码,它涉及获取以辅音开头的单词,将第一个字母移至单词末尾并添加“ ay”,并且仅在单词中添加“ ay”从元音开始。除了一些地方外,我基本上已经完成了整个项目,并且最主要的是让程序使用for循环来完成整个句子,尤其是在移至下一个列表项时

我试图在for循环的末尾做一些简单的事情,例如n + 1,并在线研究(大量研究Stackoverflow)

latin = ""
n = 0

sentence = input ("Insert your sentence ")
word = sentence.split()
first_word = word [n]
first_letter = first_word [0]
rest = first_word [1:]
consonant = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'z')
vowel = ['a', 'e', 'i', 'o', 'u')

for one in consonant :
    latin = latin + " " + rest + one + "ay"
    print (latin)
    n + 1
for one in vowel :
    latin = latin + " " + first_word +ay
    print (latin)
    n + 1

没有错误消息,但是,计算机运行的变量“ one”不是作为变量first_word的第一个(第零个)字母,而是从-z运行。有没有什么办法解决这一问题?谢谢

1 个答案:

答案 0 :(得分:0)

#!/usr/bin/env python

sentence = input("Insert your sentence ")

# don't forget "y" :)
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']

# this empty list will hold our output
output_words = list()

# we'll take the user's input, strip any trailing / leading white space (eg.: new lines), and split it into words, using spaces as separators.
for word in sentence.strip().split():
    first_letter = word[0]
    # check if the first letter (converted to lower case) is in the consonants list
    if first_letter.lower() in consonants:
        # if yes, take the rest of the word, add the lower case first_letter, then add "ay"
        pig_word = word[1:] + first_letter.lower() + "ay"
    # if it's not a consonant, do nothing :(
    else:
        pig_word = word
    # add our word to the output list
    output_words.append(pig_word)

# print the list of output words, joining them together with a space
print(" ".join(output_words))

循环遍历句子中的每个单词-无需使用n进行计数。也不需要遍历辅音或元音,我们关心的只是“这个词是否以辅音开头”-如果是,请按照您的规则进行修改。

我们将(可能)已修改的单词存储在输出列表中,完成后,我们将所有单词打印出来,并加一个空格。

请注意,此代码非常有问题-如果您的用户输入中包含标点符号,该怎么办?

I opehay hattay elpshay, eyuleochoujay