我正在尝试扩展 Codecademy pig 拉丁语转换器,以便它接受句子而不仅仅是单个单词,并转换句子中的每个单词。这是我的代码:
pyg = 'ay'
pyg_input = raw_input("Please enter a sentence: ")
print
if len(pyg_input) > 0 and pyg_input.isalpha():
lwr_input = pyg_input.lower()
lst = lwr_input.split()
for item in lst:
frst = lst[item][0]
if frst == 'a' or frst == 'e' or frst == 'i' or frst == 'o' or frst == 'u':
lst[item] = lst[item] + pyg
else:
lst[item] = lst[item][1:len(lst[item]) + frst + pyg
print ' '.join(lst)
我不确定出了什么问题,所以我很感激任何帮助。 谢谢
最佳答案
- 句子可以包含非字母(例如空格):因此 pyg_input.isalpha() 将产生 False:
- 您正在使用
lst[item]
访问每个字符。而是使用item
。 - 迭代列表时无法更新列表。在下面的代码中,我使用了另一个名为
latin
的列表。 您的代码在以下行中出现语法错误(无右括号):
lst[item][1:len(lst[item])
下面的代码并不完美。例如,需要过滤掉非字母如
、
、.
、...
pyg = 'ay'
pyg_input = raw_input("Please enter a sentence: ")
print
if len(pyg_input) > 0:# and pyg_input.isalpha():
lwr_input = pyg_input.lower()
lst = lwr_input.split()
latin = []
for item in lst:
frst = item[0]
if frst in 'aeiou':
item = item + pyg
else:
item = item[1:] + frst + pyg
latin.append(item)
print ' '.join(latin)
关于Python - Pyg 拉丁语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17908218/