在python中从文本文件创建列表

时间:2017-01-25 15:40:49

标签: python list parsing

我有一个包含以下内容的文本文件:

Matematics
Name1 Surname1
Name2 Surname2
Name3 Surname3
History
Name1 Surname1
Name2 Surname2
Name4 Surname4
Name5 Surname5

我想问一下是否可以在单独的列表中附加每个主题的所有names surnames

我可以将name surnamesubject字符串区分为:if string.count(' ') > 0:if string.count(' ') == 0:;并且在中间段落中可以将相同的符号(例如>)添加到每个subject的开头。

但我对如何生成一个为每个主题创建不同names surnames列表的循环感到困惑。

2 个答案:

答案 0 :(得分:0)

import csv
with open('file.txt', newline='') as f:
    reader = csv.reader(f, delimiter=' ')
    for row in reader:
        if len(row) == 2:
            print(row)

出:

['Name1', 'Surname1']
['Name2', 'Surname2']
['Name3', 'Surname3']
['Name1', 'Surname1']
['Name2', 'Surname2']
['Name4', 'Surname4']
['Name5', 'Surname5']

或列表理解:

lists = [row for row in reader if len(row)==2]

出:

[['Name1', 'Surname1'],
 ['Name2', 'Surname2'],
 ['Name3', 'Surname3'],
 ['Name1', 'Surname1'],
 ['Name2', 'Surname2'],
 ['Name4', 'Surname4'],
 ['Name5', 'Surname5']]

答案 1 :(得分:0)

要添加到宏杰李的回答,也许您可​​以将所有类别列表存储在dict中,如下所示:

{
    Mathematics: ['Name1 Surname1','Name2 Surname2', 'Name3 Surname3'],
    History: ['Name4 Surname4','Name5 Surname5', 'Name6 Surname6'],
}

使用:

import csv
exampleDict = {}
currentCategory = ''
with open('file.txt', newline='') as f:
    for row in reader:
        #if the row is a category (mathematics/history)
        if ' ' not in row:
            currentCategory = row
            exampleDict[currentCategory] = []
        #if the row is a 'Name Surname'
        else:
            exampleDict[currentCategory].append(row)