python - 将句子转换为 pig 拉丁语?

标签 python python-3.x

我正在尝试将句子转换为 pig latin,但无法正常工作。

条件: 1. 如果它以元音开头,在单词后面加上 way(例如 eagle become eagleway) 2.如果是辅音开头的,就查第二个字符,以此类推,只要是辅音,一直查,去掉,放在末尾。 (例如 Cereal 变成 aingr)

到目前为止,这是我的代码:

x = "The apple is extremely tasty. Great!"
y = x.split()
for i in y:
    if(i[0] == "a" or i[0]=="e" or i[0]=="i" or i[0]=="o" or i[0]=="u"):
        print(i+"way", end = " ")

我设法完成了第 1 部分。但我无法弄清楚第 2 部分。我不明白如何遍历字符并剥离整个部分。

感谢任何帮助。

谢谢。

最佳答案

首先,选择更好的变量名:

sentence = "The apple is extremely tasty. Great!"
words = sentence.split()
for word in words:

其次,您可以简化第一次检查:

    if word[0] in "aeiou":
        print("{0}way".format(word), end=" ")

最后,您可以使用 while 和切片将字符从单词的开头移动到结尾:

    else:
        while word[0] not in "aeiou":
            word = "".join((word[1:], word[0]))
        print(word, end=" ")

请注意,这仍然不能完全满足您的要求:

eTh appleway isway extremelyway asty.t eat!Gr 

我将处理字母大小写和标点符号作为练习;我建议在遍历 words 之前,将所有内容都区分大小写并删除所有标点符号。

关于python - 将句子转换为 pig 拉丁语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22862683/

相关文章:

python - Pyomo 特定范围的约束

带 url 参数的 python 模拟响应

python - 对于可能返回 None 的方法,哪种返回方式是 "better"?

python - tensorflow 中的自定义梯度 - 无法理解此示例

python - 检查 dict.items() 中的成员资格的时间复杂度是多少?

python - python3中的数据包嗅探器

python - Django 1.8 在升级到 Python 3.5 后引发错误 "module X has no attribute ' run'"

python - 名称错误 : name 'flask' is not defined

python - Pandas groupby : treat two columns as one

python 3 : TCP Client/Server Broken Pipe Error