首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Pig_Latin转换器& for循环

Pig_Latin转换器& for循环
EN

Stack Overflow用户
提问于 2019-06-18 13:14:44
回答 1查看 50关注 0票数 2

Pig拉丁语翻译器基本上是许多项目的介绍性代码,它涉及到让以辅音开头的单词将第一个字母移到单词的末尾并添加“ay”,以及只将“ay”添加到以元音开头的单词。除了一些地方,我基本上已经完成了整个项目,主要的一件事是让程序使用for循环完成整个句子,特别是在移动到下一个列表项时

我尝试过做一些简单的事情,比如在for循环的末尾执行n+1,并在网上进行了研究(主要是在Stackoverflow上)。

代码语言:javascript
复制
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

没有错误信息,但是,计算机运行变量‘1’不是作为变量first_word的第一个(第零个)字母,而是从a- z运行它。有什么办法可以修复这个问题吗?谢谢

EN

回答 1

Stack Overflow用户

发布于 2019-06-18 14:17:08

代码语言:javascript
复制
#!/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计算任何内容。也不需要遍历辅音或元音,我们所关心的是“这个单词是否以辅音开头”-如果是,请根据您的规则修改它。

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

注意,这段代码有很多buggy -如果你的用户输入包含标点符号,会发生什么呢?

I opehay hattay elpshay, eyuleochoujay

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56642125

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档