python split 函数无法按预期工作

标签 python split

我很难阐明我的问题是什么......它涉及这里的这段代码:

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/

相关文章:

python - MLKNN - __int__() 采用 1 个位置参数,但 2 个是使用 fit 方法给出的

python - 在 python 中按图像从文件中搜索谷歌图像

python - 使用 numpy Python 创建列

python - pyserial 2.7,python 3.3,发送回车

java - Java中基于双点不包括单点的分割

python - 为什么 `function` 不是 Python 中的关键字?

java - 将 .srt 文件分割成相等的 block

c++ - substr() 不会采用参数化值

java - 从文件中读取数组。 (java)

python - 使用 Python 将字符串拆分为列表