将唯一的指定实体列表写入输入文件的输出文件

时间:2014-10-28 17:12:12

标签: python

我有一个输入文本文件,格式如下,包含用户名和编程语言。我想只为输出文件编写一个唯一的编程语言列表。我想我需要生成所有编程语言的列表,然后使用set创建一个唯一的编程语言列表,然后最终将其写入输出文件。
任何有关如何更新代码的反馈都将受到欢迎。感谢

输入文件:

name: languages
Smith, John J : VBA, 
Jones, Brian Jack : Basic, assm, shell
Page, Jimmy : matlab, autocad, python
Plant, Robert P : C, C++, SQL, 
Burton, Eric : matlab, VBA, SQL, 
Frampton, Peter: VBA, basic SQL, pascal, matlab
Jagger, Mick L : 
Anderson, Ian M : C++
Joplin, Janis J : SQL, 
Morrison, Jim : C, VB, SQL, SAS, 
Hendrix, Jimmy M : python
Chang, Jackie : C,

程序:

#read file into variable line
f = open('languages_1.txt')

while True:
    list1 =[]
    list2 =[]
    # print (f)

    line = f.readline()
    if not line:
        break
    # print('Output 1', line)    

    #convert all text to lower case
    line = line.lower()
    # print('Output 2', line)

    #remove white spaces
    line = line.replace(" ", "")
    # print('Output 3', line)

    #replace commas with new line value
    line = line.strip()
    # print('Output 4', line)

    #partition each entry by :
    head, sep, tail = line.partition(':')
    # print('Output 5', line)

    #remove names and stip leading white space
    line2 = tail
    # print('Output 6', line) 

    # split each entry by ,
    list1 =line2.split(',')
    print(list1)


# the_set = set(list1)
# print(the_set)    

# outfile = open('language_list1.txt', 'w')
# outfile.write("this is line: %i\n"%i)   

2 个答案:

答案 0 :(得分:0)

你很亲密。您只需要在while循环(the_set = set())之前创建该集合,然后在while循环(the_set.update(list1))中更新它,这将为您提供一个正常运行的程序。

除此之外,你可以做几件事来清理它。首先list2看起来未使用。其次,list1不需要设置为[]作为循环中的第一行,因为该空列表只是被丢弃并替换为行{{\ n}上的拆分结果1}}。

从那里开始,我要做的下一个改变就是改变结构:

list1 =line2.split(',')

更多pythonic:

while True:
    line = f.readline()
    if not line:
         break
    # do stuff

答案 1 :(得分:0)

您只需要拆分两次并更新:

with open("Names.txt") as f:
    unique = set()
    for line in f:
        line = line.rstrip().rsplit(":",1)[-1].replace(" ","")
        unique.update(line.split(","))
    print(unique)

set(['', 'assm', 'VBA', 'shell', 'autocad', 'python', 'SQL', 'C', 'C++', 'languages', 'VB', 'pascal', 'matlab', 'Basic', 'SAS', 'basicSQL'])

rsplit(":",1)[-1]":"上拆分并获取编程语言的最后一个元素,然后.split(",")将它们分成单个单词。

你只需要遍历文件对象,python将在到达EOF时结束循环。 同时使用with打开文件是最好的方法,因为它会自动关闭它们。