2014-03-31 83 views
0

所以我有一個需要一個句子並返回到明膠中的函數。代碼如下:當我輸入一個字,但是當我輸入一個句子就進入瘋狂將一個句子轉換成明膠

import re 
from string import ascii_uppercase 

def isvowel(ch): 
    vowels = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U") 
    for i in range(len(ch)): 
     if ch[i] in vowels: 
      return i 
    return -1 


def format(ch): 
    if any(x in ascii_uppercase for x in ch): 
     ch = ch.capitalize() 
    m = re.search(r'\W+', ch) 
    if m: 
     ch = ch.replace(m.group(0), '') + m.group(0) 
    return ch 


def igpay(astring): 
    vowels = ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U") 
    words = astring.split() 
    count = 0 
    for ch in words: 
     vowel = isvowel(ch) 
     if vowel == 0: 
      astring = astring.replace(ch,(format(ch + "way"))) 
     else: 
      astring = astring.replace(ch,(format(ch[vowel:] + ch[:vowel] + "ay"))) 
    astring = astring.strip()   
    return astring 

輸出工作正常。

例子: 即時得到什麼:

>>>igpay("An apple a day keeps the doctor away") 
>>>'Anwawaywayy awaywaypplewawaywayy awayway dawaywayy eepskay ethay octorday  awaywaywawaywayy' 

我應該得到什麼:

>>>igpay("An apple a day keeps the doctor away") 
>>>'Anway appleway away ayday eepskay ethay octorday awayway' 

如果我單獨輸入每個字,我得到一個正確的返回。到底是怎麼回事?

+0

Icenay ogrampray :) –

回答

1

這是因爲您正在修改循環中的整個句子來替換單詞結尾。

相反,你應該這樣做對列表中的每個字,收集字列表,並返回他們的空間加入:

def igpay(astring): 
    words = astring.split() 
    modified_words = [] 
    for ch in words: 
     vowel = isvowel(ch) 
     if vowel == 0: 
      ch = ch.replace(ch, (format(ch + "way"))) 
     else: 
      ch = ch.replace(ch, (format(ch[vowel:] + ch[:vowel] + "ay"))) 
     modified_words.append(ch.strip()) 
    return ' '.join(modified_words) 

用法示例(正是你要找的人):

>>> igpay("An apple a day keeps the doctor away") 
'Anway appleway away ayday eepskay ethay octorday awayway'