我很难阐明我的问题是什么......它涉及这里的这段代码:
def txt_to_dict_ad():
my_dict = {}
with open('database.txt', 'r') as file:
for line in file:
temp = list(line.strip().split('-'))
my_dict[temp[1].strip('\n')] = temp[0]
return my_dict
当我运行它并且例如想要打印该函数的输出时,我收到包含 temp[1] 和 temp[0] 的行的“索引超出范围”错误。这是为什么?我怎样才能避免它?
txt 文件包含阿拉伯语和德语词汇, 示例数据:汽车 - 斯亚瑞埃
最佳答案
如果database.txt
中的一行不包含-
,然后变量 temp
包含一个仅包含一个元素的列表和 temp[1]
下一行的尝试访问不存在的第二个元素,因此会抛出错误。
您可以通过忽略没有 -
的行来避免错误。 ,例如。
if '-' in line:
temp = list(line.strip().split('-'))
my_dict[temp[1].strip('\n')] = temp[0]
如果您想识别没有连字符的行:
with open('database.txt', 'r') as file:
for i, line in enumerate(file, start=1):
if '-' in line:
temp = list(line.strip().split('-'))
my_dict[temp[1].strip('\n')] = temp[0]
else:
print('Line {} misses the underscore.'.format(i))
关于python split 函数无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44609636/