我不知道怎么了

2024-05-21 03:12:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个函数来实现打开一个文件->;选择某一列->;去掉不重复的名字->;把名字写进另一个文件。 我写了一些这样的代码:

def method2(filename):
    name = filename + '.txt'
    content = open(name,'r')

    for line in content:
        values = line.split()
        a = values[1]

        print(a)

错误是:

>>> method2('test')
d8:c7:c8:5e:7c:2d,
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    method2('test')
  File "C:/Users/Yifan/Desktop/data/Training data/Method2.py", line 10, in method2
    a = values[1]
IndexError: list index out of range

我的文件如下所示:

  1405684432,        d8:c7:c8:5e:7d:e8,          SUTD_Guest,   57



  1405684432,        d8:c7:c8:5e:7c:89,           SUTD_ILP2,   74



  1405684432,        d8:c7:c8:5e:7c:8d,           SUTD_GLAB,   74



  1405684432,        b0:c5:54:dc:dc:6c,              ai-ap1,   85

Tags: 文件nameintestgtlinecontentfilename
2条回答

给你

测试.py

def read_file(filename):
    file = open(filename)
    contents = map(str.strip,file.readlines())
    file.close()
    return contents

def get_column_values(col_num,lines):
    column_values = []

    for line in lines:
        if not line:
            continue

        values = line.split()

        #col_num - 1 = index of list
        #[:-1] will chop the last char i.e. comma from the string
        column_values.append(values[col_num-1][:-1])

    return column_values

def remove_duplicates(xList):
    return list(set(xList))


def write_file(filename,lines):
    file = open(filename,"w")
    for line in lines:
        file.write("%s\n" % line)
    file.close()


def main():
    lines = read_file("input.txt")

    #Work on 1st Column i.e. 0th index
    column_values = get_column_values(1,lines)
    entries = remove_duplicates(column_values)
    write_file("output.txt",entries)

main()

输入文件

1405684432,        d8:c7:c8:5e:7d:e8,          SUTD_Guest,   57

1405684432,        d8:c7:c8:5e:7c:89,           SUTD_ILP2,   74

1405684432,        d8:c7:c8:5e:7c:8d,           SUTD_GLAB,   74

1405684432,        b0:c5:54:dc:dc:6c,              ai-ap1,   85

输出.txt 1405684432个

当您到达第二行(看起来是空的)并将其拆分时,只会在values中得到一个空列表。尝试访问元素1,即第二个元素失败,因为没有第二个元素。你知道吗

试着把if len(values) > 0:放进去保护a = line[1]。你知道吗

相关问题 更多 >