2014-04-01 83 views
-2

我被困在一個非常困難的問題中,我需要在給定的字符串中爲Python創建一個Pig Latin轉換器。Python:豬拉丁函數

基本上,這裏是規則。

  1. 對於與一個或多個輔音開始(y被認爲是輔音)的任何字: 輔音移到字的末尾和追加字符串「AY」。

  2. 對於所有其他單詞,將字符串'way'追加到末尾。

該功能還必須區分處理標點符號和大小寫,因此建議大家創建一個單獨的功能來找到任何單詞的首元音和使用它的主要功能,這點我還挺做,然而,我在執行案例和標點符號時遇到了麻煩,無法應用到我的主要公式中,如果一個詞沒有元音,該怎麼辦(因爲在我們的例子中「y」不算作元音,「我的」這個詞不會有一個元音。

這裏是我到目前爲止的代碼。

def vowelfinder(astring): 
    vowels = ["A","E","I","O","U","a","e","i","o","u"] 
    alist = astring.split() 
    for i in alist: 
     for j in range(len(i)): 
      if i[j] in vowels: 
       print(j) 
       break 

def igpay(astring): 
    vowelfinder(astring) 
    for i in alist 

任何ADVI ce有幫助

+1

爲什麼不讓你的同學和你每個任務發佈一個問題?這就像今天的第五個豬拉丁問題。只要在SO上搜索「拉丁名字」,你就會找到其他學生問題的答案。 – Hyperboreus

+0

[這個答案顯示瞭如何使用're.split()'和'str.isalnum()']處理標點符號(http://stackoverflow.com/a/22776429/4279)。 – jfs

回答

0
# For any word that begins with one or more consonants (y is considered a consonant): 
if "aeiouAEIOU".find(astring[0]) == -1: 
    # move the consonants to the end of the word and append the string 'ay'. 
    return astring[1:] + astring[0] + "ay" 
# For all other words, 
else: 
    # append the string 'way' to the end. 
    return astring + "way" 

這是一個詞。分詞應該很容易。

編輯:brainfart。

+1

使用'if astring [0]不在'aeiouAEIOU':'而不是'.find()'方法。 – jfs