首页 > 解决方案 > 为什么我的 piglatin 翻译代码给出了意外的输出?

问题描述

我建立了一个有趣的项目,名为 piglatin 翻译器。它遵循两个原则。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)

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

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

标签: python-3.x

解决方案


您需要取消缩进以开头的行,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)

推荐阅读