如何在读取 csv 文件时修复列表索引超出范围

问题描述 投票:0回答:1

这是我的代码:

 with open('kamus_singkatan.csv', 'r') as file:
        data = file.read().rstrip()
        print(data)

输出:

arr = data.split('\n')
arr

输出:

代码:

arr = [a.split(';') for a in arr]
arr

输出:

这是我出错的时候:

cor = {kv[0].strip(): kv[1].strip() for kv in arr}
cor

请帮助我

python jupyter-notebook normalization sentiment-analysis outofrangeexception
1个回答
0
投票

您可以遍历列表并检查每个子列表的长度(=2 和 !=2(特殊情况)),然后对每种情况执行您想要的操作

lst = [["a ", "b  "], ["c ", "d  "], ["e  ", "f"], [" g"]]

my_dict = {}

for sublst in lst:
    if len(sublst) == 2: # Normal case, there are 2 values in a list
        key = sublst[0].strip()
        value = sublst[1].strip()
        my_dict[key] = value
    elif len(sublst) != 2: # Special case, for example 1 value in a list
        key = sublst[0].strip() # Set the value in the list be the key of the dict
        my_dict[key] = "special_case" # The value of the dict is a character you choose

print(my_dict) # {'a': 'b', 'c': 'd', 'e': 'f', 'g': 'special_case'}
© www.soinside.com 2019 - 2024. All rights reserved.