简体   繁体   English

python不知道怎么了

[英]python no idea what's wrong

I want write a function to achieve open a file->choose a certain column->take out the non repeated names->write the names into another file. 我想编写一个函数来实现打开文件->选择某个列->取出不重复的名称->将名称写入另一个文件。 I have written some code like this: 我写了一些这样的代码:

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

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

        print(a)

the error is: 错误是:

>>> 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

my file looks like this: 我的文件如下所示:

  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

When you reach the second line, which looks empty, and split it, you only get an empty list in values . 当您到达第二行时,该行看起来为空,并将其拆分,您只会在values获得一个空列表。 Trying to access element 1 , ie the second, fails, because there is no second element. 尝试访问元素1 (即第二个元素)失败,因为没有第二个元素。

Try putting if len(values) > 0: in there to protect a = line[1] . 尝试将if len(values) > 0:放入其中以保护a = line[1]

Here you go 干得好

test.py test.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()

input.txt input.txt中

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

output.txt 1405684432 output.txt 1405684432

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

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