所以我有一个功能,它会在一个句子中并在piglatin中返回。代码如下:
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 :(得分: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'