Pig\u拉丁文翻译for loop

2024-07-03 05:54:10 发布

您现在位置:Python中文网/ 问答频道 /正文

Pig-Latin translator基本上是许多项目的入门代码,它涉及到让以辅音开头的单词将第一个字母移动到单词的末尾并添加“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的第一个(零)字母,而是从a-z运行它。有办法解决这个问题吗?谢谢


Tags: 项目restfor字母单词事情onesentence
1条回答
网友
1楼 · 发布于 2024-07-03 05:54:10
#!/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

相关问题 更多 >