so, I was wondering how I could split the lines of a file and put them into a list? I tested out a code that works for one segment of the list but not the other chunks:
The file looks like:
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
and so forth.
This is the code for the first half, riding 0: line = f.readline()
while line !='':
district = str.split(line)
line = f.readline()
a.append(district)
print(a)
And this is the code I did for the second half:
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()
When I print it's just a blank space. I was wondering if anyone could help out. The output should look be a lists of lists for each riding. So, for Riding 0: it'd be [[line 1], [line 2] etc] and Riding 1: [[line 1], [line 2]] etc.
This should solve it for you -
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']]}
So that is my code for you. hope it work
FileStream f = new Filestream(path,FileMode.Open);
StreamReader sf = new StreamReader(f);
Here
while !sf.EndOfStream:
district = str.split(' ')
line = f.readline()
a.append(district)
print(a)
you fail at str.split(' ')
;
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)
Output:
[[['NDP', 'LIBERAL', 'GREEN', 'CPC'], ['NDP', 'GREEN', 'LIBERAL', 'CPC'], ['CPC', 'LIBERAL', 'GREEN', 'NDP'], ['NDP', 'GREEN', 'LIBERAL', 'CPC']]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.