python-3.x - 为什么我的 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”
解决方案
您需要取消缩进以开头的行,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)
推荐阅读
- java - 如何判断以字符串表示的十进制数是否适合双精度数?
- c# - ASP.NET Core 中的 HttpContext RESPONSE END 如何
- internet-explorer-11 - 如何防止 Apollo 客户端查询在 IE11 中缓存?
- metal - 函数(depthwiseConvolution):在 lM[0] 的索引 0 处缺少 threadgroupMemory 绑定
- module - 有什么方法可以让 ModuleScript 像常规代码一样运行?
- azure-devops - VSTS 无法查询团队
- jmeter - 非GUI模式下获取测试计划目录
- python - 在 python 中用大文件绘制集群热图?
- php - 合并时间段 - php
- javascript - 动态使用 DOMFormControlElement 设置值