使用Python字典实现字符串逐行对照翻译时遇类型错误求助
问题:希腊语翻译函数的索引错误
我尝试用Python字典实现字符串翻译,把翻译后的英文单词追加到列表生成逐行对照翻译,但遇到两个问题:
- 使用
.append(lexicon[word['English']])时触发TypeError: string indices must be integers错误; - 直接用
.append(lexicon[word])会把包含发音、英文翻译等信息的整个子字典追加到列表里,不是我要的纯翻译内容。
我的代码
#imperts-------------------------------------------------------------------------------------------- #I have no clue what any of this means from lexicon import lexicon #Define Isopsephy ---------------------------------------------------------------------------------- #alpha AND numeric?! #from isopsephy import isopsephy #cold-barrel test___________________________________________________________________________________ #what are we reading from anyway? john_1_1_greek = 'Ἐν ἀρχῇ ἦν ὁ Λόγος, καὶ ὁ Λόγος ἦν πρὸς τὸν Θεόν καὶ Θεὸς ἦν ὁ Λόγος.' john_1_1_english = [] #Translate function--------------------------------------------------------------------------------- def translate(): for word in john_1_1_greek.split(" "): if word in lexicon.items(): john_1_1_english.append(lexicon[word['English']]) return word #run the function----------------------------------------------------------------------------------- translate() #john1_1_isopsephy = [] #test print print(john_1_1_greek) print(john_1_english)
词典示例
'Ἐν': { 'word': 'Ἐν', 'pronunciation': 'En', 'English': 'In [the]'},
报错信息
Traceback (most recent call last): File "C:\Users\turds\PycharmProjects\pythonProject\main.py", line 23, in translate() File "C:\Users\turds\PycharmProjects\pythonProject\main.py", line 18, in translate john_1_1_english.append(lexicon[word['English']]) TypeError: string indices must be integers
问题原因与修复方案
错误根源
- 字符串索引误用:
word是拆分后得到的字符串(比如'Ἐν'),word['English']试图用字符串索引字符串,而字符串只能用整数索引,因此触发错误。正确的做法是先通过lexicon[word]取出对应子字典,再用['English']获取翻译内容。 - 存在性判断错误:
lexicon.items()返回的是键值对元组,if word in lexicon.items()永远不会匹配,应该用if word in lexicon检查单词是否是词典的键。 - 循环提前终止:函数内的
return word会让循环只执行一次就退出,导致只有第一个单词被处理。
修正后的代码
# 导入词典模块 from lexicon import lexicon # 待翻译的希腊语文本 john_1_1_greek = 'Ἐν ἀρχῇ ἦν ὁ Λόγος, καὶ ὁ Λόγος ἦν πρὸς τὸν Θεόν καὶ Θεὸς ἦν ὁ Λόγος.' john_1_1_english = [] def translate(): for word in john_1_1_greek.split(" "): # 检查当前单词是否在词典中 if word in lexicon: # 取出对应子字典中的英文翻译并追加 john_1_1_english.append(lexicon[word]['English']) else: # 处理未收录的单词,直接保留原词 john_1_1_english.append(word) # 执行翻译 translate() # 打印对照结果 print(john_1_1_greek) print(john_1_1_english)
修正说明
- 调整索引方式:
lexicon[word]['English']先获取单词对应的子字典,再提取翻译内容; - 修复存在性判断:用
word in lexicon正确检查单词是否存在于词典键中; - 移除循环内的
return语句,确保所有单词都被遍历处理; - 增加
else分支,避免未收录单词导致程序报错,同时保留原词便于对照。
内容的提问来源于stack exchange,提问作者Eddard Greybeard
相关产品推荐
相关产品推荐

