Python自定义语言生成器多the场景按索引翻译错误问题排查
问题根因
你遇到的翻译错误是list.index()方法的特性导致的:该方法始终返回列表中第一个匹配元素的下标,当句子里存在多个the时,每次匹配到the都会定位到第一个the的位置,取它后面的名词man判断阴阳性,因此所有the都会被错误翻译为de。
修复方案
遍历单词时同步记录当前单词的索引,直接用当前索引取后一位相邻单词即可,同时补充边界判断避免the出现在句尾时触发索引越界错误。
核心代码修改
第一步,修改遍历语句,同步获取索引:
# 原代码 for word in split: # 修改后 for idx, word in enumerate(split):
第二步,修改the的翻译逻辑:
elif word == 'the': # 先判断the不在句尾,避免索引越界 if idx < len(split) - 1: c = split[idx + 1] if c in originalNounM: translated_sentence += 'de' elif c in originalNounF: translated_sentence += 'di'
完整可运行修复版代码
import string originalNounM = ['man', 'rock'] newNounM = ['mno', 'lehr'] originalNounF = ['woman', 'chair'] newNounF = ['felio', 'poenter'] originalVerb = ['sit'] newVerb = ['colt'] originalA = ['a'] newA = ['es', 'en'] def translate(): sentence = input('Enter the sentence to turn into your custom language! ') split = sentence.split() translated_word = [] translated_list = [] translated_sentence = '' for idx, word in enumerate(split): char = '' translated_word.clear() for i in word: translated_word += i word = '' for a in string.punctuation: if str(a) in translated_word: char = a translated_word.remove(str(a)) for i in translated_word: word += i if word in originalNounM: t = originalNounM.index(word) translated_sentence += newNounM[t] elif word in originalNounF: t = originalNounF.index(word) translated_sentence += newNounF[t] elif word in originalVerb: t = originalVerb.index(word) translated_sentence += newVerb[t] elif word == 'the': if idx < len(split) - 1: c = split[idx + 1] if c in originalNounM: translated_sentence += 'de' elif c in originalNounF: translated_sentence += 'di' else: translated_sentence += word word += str(char) word += ' ' for i in translated_sentence: translated_list += i translated_list += str(char) translated_list += ' ' translated_sentence = '' leng = len(translated_list) - 2 final = translated_list[leng] if final in string.punctuation: translated_list.remove(final) translated_sentence = '' for i in translated_list: translated_sentence += i if final in string.punctuation: translated_sentence += final print(translated_sentence) other_translate = input('Would you like to translate another sentence? y/n ') if other_translate == 'y': translate() translate()
优化建议
- 原代码的标点处理逻辑可简化,无需转列表删除,可直接用字符串方法提取有效内容
- 递归调用
translate()可能触发调用栈溢出,建议改用while循环控制是否继续翻译 - 可改用字典存储原词与译词的映射关系,替代多列表+index查找,执行效率更高,逻辑也更清晰
内容的提问来源于stack exchange,提问作者qwerteee
相关产品推荐
相关产品推荐

