我正在尝试在python中构建一个英语到猪拉丁语的转换程序。我的程序成功将所有英语单词转换为Pig Latin单词。但我不明白如何将标点符号放在猪拉丁语句中的同一位置,就像在原始英语句子中一样。我转换了标点符号,无论是在单词的最后一位还是第一位,但是我无法转换像撇号(' s)这样的单词之间的标点符号或者像问号(?)一样的两个标点符号。句子关闭单/双引号(' /")等。这是我的代码:
import string
import random
def take_input(sentence):
prefix=[]
stem=[]
word_ans=[]
punc=[]
sent_ans=[]
for word in sentence.split():
word=list(word)
for i in range(len(word)):
if word[i] in ('A','E','I','O','U','Y','a','e','i','o','u','y'):
stem=word[i:]
break
else:
prefix.append(word[i])
for x in stem:
word_ans.append(x)
for x in prefix:
word_ans.append(x)
word_ans.append('a')
word_ans.append('y')
if word[-1] in string.punctuation:
word_ans.remove(word[-1])
word_ans.append(word[-1])
if word[0] in string.punctuation:
word_ans.remove(word[0])
word_ans[1:]=word_ans
word_ans[0]=word[0]
for i in word_ans:
sent_ans.append(i)
sent_ans.append(' ')
del prefix[:]
del stem[:]
del word_ans[:]
sent_answer=''.join(sent_ans)
return sent_answer
Answer=take_input("'Hi, How are you?'")
print Answer
期望的输出:' iHay,owHay areay youay?'
当前输出:我' Hay,owHay areay you?ay'
答案 0 :(得分:0)
你最好的选择是使用正则表达式:
import re
text = 'Hi, how are you? I am fine.'
tokens = re.split("(\W)", text)
pig_tokens = map(lambda t: t if not re.search('\w', t) else t[-1].upper() + t[:-1].lower() + 'ay', tokens)
print ''.join(pig_tokens) # Ihay, Whoay Earay Uyoay? Iay Maay Efinay.