为什么我的Piglatin转换器代码给出了意外的输出?

时间:2019-04-26 00:53:26

标签: python-3.x

我建立了一个有趣的项目,名为Piglatin Translator。它基于两个原则。 1.如果句子中的单词以元音开头,则在单词的最后加上“ yay”。 2.如果单词以辅音开头。在词组末尾的常数簇中找到元音并添加“ ay”

# Ask for the sentence
original=input("Enter the string.:").strip().lower()
# split the sentence
words=original.split()

# Loop through words and convert to pig latin
new_words=[]
for word in words:
  if word[0] in "aeiou":
    new_word=word+"yay"
    new_words.append(new_word)        
  else:
    vowel_pos=0
    for letter in word:
        if letter not in "aeiou":
            vowel_pos=vowel_pos+1
        else:
            break
        cons=word[:vowel_pos]
        the_rest=word[vowel_pos:]
        new_word=the_rest+cons+"ay"
        new_words.append(new_word)

#If start with vowel then add yay

# Transfer the constant cluster at the end and add ay

# Join the words
output=" ".join(new_words)
# Output the final string
print(output)

我已经构建了代码。现在,每当我给 我的名字叫希哈卜 输出显示 “ ymay myay amenay isyay hihabsay ihabshay”

我期望的输出是:  “ myay amenay isyay ihabshay”

1 个答案:

答案 0 :(得分:1)

您需要取消缩进以cons=word[:vowel_pos]开头的行,因为每个字母都在尝试找到第一个元音时正在运行,并且只希望在找到元音位置或到达末尾后再运行一次这个词。

# Ask for the sentence
original=input("Enter the string.:").strip().lower()
# split the sentence
words=original.split()

# Loop through words and convert to pig latin
new_words=[]
for word in words:
  if word[0] in "aeiou":
    new_word=word+"yay"
    new_words.append(new_word)        
  else:
    vowel_pos=0
    for letter in word:
        if letter not in "aeiou":
            vowel_pos=vowel_pos+1
        else:
            break
    cons=word[:vowel_pos]
    the_rest=word[vowel_pos:]
    new_word=the_rest+cons+"ay"
    new_words.append(new_word)

#If start with vowel then add yay

# Transfer the constant cluster at the end and add ay

# Join the words
output=" ".join(new_words)
# Output the final string
print(output)