Ben Fisher
Ben Fisher

Reputation: 69

Python: split file into mulitple lists by empty lines

I have the following text file:


Singapore Smith's Crew

Leader
Singapore Smith
d10
3d8
3d10
3d10
2d8
3d10
2d10
Sharp
Deadeye
Hardened Veteran

Sidekick
Arge
d8
4d8
3d8
2d6
3d8
2d6
2d6
Athletic
Fierce

Ally
Enki
d6
2d6
3d6
1d6
1d6
1d6
1d6
Marksman

Ally
Kazak
d6
2d6
3d6
1d6
1d6
1d6
1d6
Marksman

Ally
Little Skeet
d6
1d6
1d6
2d6
1d6
1d6
2d6
Crafty

I would like to split them into multiple lists in python to have for example the following structure:

["Singapore Smith's Crew]
[Leader, Singapore Smith, d10, 3d8. etc.]
[Sidekick, Argue, d8, etc.]

and so on...

Does somebody knows how to do that? The idea is that I can send the arrays afterwards to Character classes to instantiate objects.

Thanks in advance

Upvotes: 1

Views: 240

Answers (1)

Mark
Mark

Reputation: 92430

You can pass your file into itertools.groupby with a key that specifies the line (after stripping whitespace) is not empty. Then make lists of the non-empty groups:

from itertools import groupby

path = "some/file/path"

with open(path) as f:
    l = [list(g) for k, g in groupby(map(str.strip, f), key=lambda line: line != '') if k]
    print(l)

This prints:

[["Singapore Smith's Crew"], ['Leader', 'Singapore Smith', 'd10', '3d8', ...],..etc]

groupby makes an iterator, so you can alternatively loop over the values if you don't want to make a big list:

for k, g in groupby(map(str.strip, f), key=lambda line: line != ''):
    if k:
       # use g

Upvotes: 1

Related Questions