简体   繁体   English

Python错误:IndexError列表索引超出范围

[英]Python Error: IndexError list index out of range

 file = open(selection, 'r')
 dict = {}
 with open(selection, 'r') as f:
    for line in f:
        items = line.split()
        key, values = items[0], items[1:]
        dict[key] = values
 englishWord = dict.keys()
 spanishWord = dict.values()

Hello, I am working on a project where I have an file with spanish and english words. 您好,我正在一个项目中,我有一个包含西班牙语和英语单词的文件。 I am trying to take these words, and put them into a dictionary. 我正在尝试将这些单词放入字典中。 The file looks like this: 该文件如下所示:

library, la biblioteca 图书馆
school, la escuela 埃斯库埃拉学校
restaurant, el restaurante 餐厅,餐厅
cinema, el cine 电影院,电影院
airport, el aeropuerto 机场,埃尔埃罗普埃尔托
museum, el museo 博物馆,博物馆
park, el parque 帕克公园
university, la universidad 大学
office, la oficina 办公室,la oficina
house, la casa 房子,拉卡萨

Every time I run the code, I get an error about the range. 每次运行代码时,都会出现有关范围的错误。 What am I doing wrong? 我究竟做错了什么?

You probably have empty lines in your file, resulting in empty items -list: 您的文件中可能有空行,从而导致空items -list:

dict = {}
with open(selection, 'r') as lines:
    for line in lines:
        items = line.split()
        if items:
            key, values = items[0], items[1:]
            dict[key] = values

You do not need to open the file first if you need with! 如果需要,您不需要先打开文件! Also you need to specify what the character used for splitting needs to be, otherwise it splits on every whitespace and not on ',' as you want it to. 另外,您还需要指定用于拆分的字符,否则,它会在每个空格上拆分,而不是在您希望的''上拆分。 This code works (assuming your file is called 'file.txt'): 此代码有效(假设您的文件名为“ file.txt”):

dict = {}
with open('file.txt', 'r') as f:
    for line in f:
        items = line.split(',')
        print(items)
        key, values = items[0], items[1:]
        dict[key] = values
englishWord = dict.keys()
spanishWord = dict.values()

Check to make sure you don't have empty lines. 检查以确保您没有空行。

dict = {}
with open(selection, 'r') as lines:
    for line in lines:
        items = line.split()
        if (len(items) > 1):
            if items:
                key, values = items[0], items[1:]
                dict[key] = values

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM