Python实现Pig Latin转换时丢失末尾标点符号原因排查
Pig Latin转换标点丢失问题修复
存在的问题
- 末尾字符提取逻辑错误:原代码中
lastChar = (word[len(word) - 1:-2:-1])的切片写法会返回倒序截取的长度为2的字符串,而非单个末尾字符,导致标点判断条件永远不触发,havePunct始终为False。正确的末尾字符提取写法为lastChar = word[-1]。 - 标点追加逻辑错误:原代码即使判断到存在标点,也仅在转换结果后追加空格,没有存储并追加实际匹配到的标点符号。
- 转换结果末尾冗余空格:原代码中拼接
way、ay时末尾带了多余空格,不符合输出要求。 - 转换逻辑存在重复执行问题:原代码没有对元音开头、辅音开头的逻辑做分支互斥,元音开头的单词会先被拼接
way,后续又被for循环的逻辑覆盖为ay结尾的结果,不符合Pig Latin规则。
修复后代码
def convertWord(word): convertedWord = "" listVowels = ["a","e","i","o","u"] listPunctuation = ["!",".",",","?"] havePunct = False punctuation = "" # 提取末尾字符判断是否为标点 lastChar = word[-1] if lastChar in listPunctuation: havePunct = True punctuation = lastChar word = word[:-1] # 元音开头处理逻辑 if word[0:1].lower() in listVowels: convertedWord = word + "way" # 辅音开头处理逻辑 else: for letter in word: if letter.lower() in listVowels: posVowel = word.index(letter) beginWord = word[0:posVowel] convertedWord = word[posVowel:] + beginWord + "ay" break # 追加存储的标点符号 if havePunct: convertedWord = convertedWord + punctuation # 首字母大写适配 if word[0:1].isupper(): convertedWord = convertedWord.capitalize() return convertedWord def main(): print(convertWord("Science!")) main()
运行上述代码,输入Science!时输出结果为Iencescay!,完全符合预期。
内容的提问来源于stack exchange,提问作者jumbopushpo112
相关产品推荐
相关产品推荐

