如何从文本文件中提取特定行并存储在列表中(python)

时间:2014-04-26 20:35:01

标签: python

我有一个文本文件,格式如下:

356693

2013 46,  2013 67,  2013 47,  2013 63,  2013 59,  2013 76
MECN1001, MECN1003, CHEM1033, MATH1014, PHYS1014, PHYS1015

522021

2009 45,  2009 49,  2009 67,  2009 54,  2009 67,  2009 83,  2010 46,  2010 91,  2010 42,  2010 60,  2010 52,  2011 61,  2011 65,  2011 56,  2012 53,  2012 54,  2012 45,  2012 45,  2012 43,  2012 63,  2013 66,  2013 62,  2013 50,  2013 83,  2013 69,  2013 74,  2013 100
MECN1001, MECN1003, CHEM1033, MATH1014, PHYS1014, PHYS1015, MECN1001, MECN1003, MECN2011, ELEN2000, MATH2011, MECN1001, MECN2006, MECN2011, MECN2000, MECN2005, MECN2010, MECN2012, MECN2013, MECN2014, MECN2010, MECN2012, MECN2013, MECN3002, MECN3010, MECN3028, MATH3026

数字356693522021是特定的学号。

现在我已经打开文件并读取了这些行,但我想只提取学生编号的行并将其存储在一个单独的列表中。如何仅提取学生编号的行?

(请记住,文本文件包含的数据远不止这些,我刚刚拿这篇文章来获取帮助)

4 个答案:

答案 0 :(得分:0)

您可以逐行读取文件,将每一行解析为其组成字段,并检查该行中的字段数。如果只有1个字段,则为用户编号。

f = open("data_file")
for line in f:
    data = line.strip().split(',')
    if len(data) == 1:
        print data[0]

答案 1 :(得分:0)

您可以尝试使用几个条件的循环。例如:

s = """356693

2013 46, 2013 67, 2013 47, 2013 63, 2013 59, 2013 76 MECN1001, MECN1003, CHEM1033, MATH1014, PHYS1014, PHYS1015

522021

2009 45, 2009 49, 2009 67, 2009 54, 2009 67, 2009 83, 2010 46, 2010 91, 2010 42, 2010 60, 2010 52, 2011 61, 2011 65, 2011 56, 2012 53, 2012 54, 2012 45, 2012 45, 2012 43, 2012 63, 2013 66, 2013 62, 2013 50, 2013 83, 2013 69, 2013 74, 2013 100 MECN1001, MECN1003, CHEM1033, MATH1014, PHYS1014, PHYS1015, MECN1001, MECN1003, MECN2011, ELEN2000, MATH2011, MECN1001, MECN2006, MECN2011, MECN2000, MECN2005, MECN2010, MECN2012, MECN2013, MECN2014, MECN2010, MECN2012, MECN2013, MECN3002, MECN3010, MECN3028, MATH3026"""

toks = s.split()

student_numbers = []

for token in toks:
    if token.isdigit() and len(token) == 6:
        print 'Student # %s' % (token)
        student_numbers.append(token)

print len(student_numbers), ' student numbers found'        

"""
--Outputs--

Student # 356693
Student # 522021
2  student numbers found
"""

答案 2 :(得分:0)

我建议逐行浏览文件,并针对每一行检查regular expression以查看它是否是一个6位数字。如果是,请将其打印出来。

import re
student_num = re.compile("[0-9]{6}") // 6 digits
with open("data_file") as f:
    for line in f:
        if student_num.match(line.strip()):
            print line.strip()

或者,如果所有数据都采用上面给出的格式,则您不需要正则表达式,而是可以依赖行长度,例如:

with open("data_file") as f:
    for line in f:
        if len(line.strip())==6:
            print line.strip()

但是,如果任何机会格式不能完全一致,我会使用正则表达式版本,因为它更准确地匹配。

答案 3 :(得分:0)

你可以使用这样的列表理解:

with open("data_file") as f:
    print [x.strip() for x in f if x.strip().isdigit()]

这会删除行并检查返回值是否为数字,它会在结果列表中接受它。

,输出结果为:

['356693', '522021']

希望这会有所帮助。