python - Splitting Lines and Lines -
so, wondering how split lines of file , put them list? tested out code works 1 segment of list not 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 forth.
this code first half, riding 0: line = f.readline()
while line !='': district = str.split(line) line = f.readline() a.append(district) print(a)
and code did 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 print it's blank space. wondering if out. output should lists of lists each riding. so, riding 0: it'd [[line 1], [line 2] etc] , riding 1: [[line 1], [line 2]] etc.
this should solve -
import re f = open('x.txt') d = [l.strip() l in f.readlines() if l.strip()] groups = {} curr_key = '' 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']]}
Comments
Post a Comment