0

所以,我想知道如何拆分文件的行并将它们放入列表中?我测试了一个适用于列表的一部分但不适用于其他块的代码:

该文件如下所示:

Rank Ballots

Riding 0

NDP LIBERAL GREEN CPC

NDP GREEN LIBERAL CPC

CPC LIBERAL GREEN NDP

NDP GREEN LIBERAL CPC


Riding 1

NDP LIBERAL GREEN CPC

LIBERAL GREEN NDP CPC

NDP GREEN LIBERAL CPC

LIBERAL GREEN NDP CPC

NDP GREEN LIBERAL CPC

等等。

这是前半部分的代码,骑0:line = f.readline()

 while line !='':
    district = str.split(line)
    line = f.readline()
    a.append(district)
print(a)

这是我为后半部分所做的代码:

header = f.readline().rstrip() 
riding = f.readline().rstrip()
riding = f.readline().rstrip()
votes = []

while riding !='':
    rank = str.split(riding)
    votes = []
    while rank != '':
        votes.append(rank)
        rank = str.split(riding)
        riding = f.readline().rstrip()

    print(votes)
    riding = f.readline().rstrip()

当我打印它只是一个空白区域。我想知道是否有人可以帮忙。输出应该是每个骑行的列表。所以,对于 Riding 0:它会是 [[line 1], [line 2] etc] 和 Riding 1: [[line 1], [line 2]] 等等。

4

3 回答 3

0
lines = [L.strip() for L in f if L.strip()][1:]

data = []
group = []

for L in lines:
    if L.startswith('Riding'):
        if group:
            data.append(group)
        group = []
        continue
    group.append(L.split())

print(data)

输出:

[[['NDP', 'LIBERAL', 'GREEN', 'CPC'], ['NDP', 'GREEN', 'LIBERAL', 'CPC'], ['CPC', 'LIBERAL', 'GREEN', 'NDP'], ['NDP', 'GREEN', 'LIBERAL', 'CPC']]]
于 2013-04-05T02:05:42.793 回答
0

这应该为您解决 -

import re

f = open('x.txt')
d = [l.strip() for l in f.readlines() if l.strip()]

groups   = {}
curr_key = ''
for line in d:
    if re.search('Riding [0-9]+', line):
        curr_key = line
        groups[curr_key] = []
    elif curr_key:
        groups[curr_key].append([line])

print groups

>>> {'Riding 1': [['NDP LIBERAL GREEN CPC'], ['LIBERAL GREEN NDP CPC'], ['NDP GREEN LIBERAL CPC'], ['LIBERAL GREEN NDP CPC'], ['NDP GREEN LIBERAL CPC']], 'Riding 0': [['NDP LIBERAL GREEN CPC'], ['NDP GREEN LIBERAL CPC'], ['CPC LIBERAL GREEN NDP'], ['NDP GREEN LIBERAL CPC']]}
于 2013-04-05T01:57:44.280 回答
0

这就是我给你的代码。希望它有效

FileStream f = new Filestream(path,FileMode.Open);
StreamReader sf = new StreamReader(f);

这里

while !sf.EndOfStream:
    district = str.split(' ')
    line = f.readline()
    a.append(district)
print(a)

你失败了str.split(' ')

于 2013-04-05T02:00:45.620 回答