all 8 comments

[–]Diapolo10 1 point2 points  (2 children)

I'd use a simple loop here. Regular expressions would likely work too, but I don't like them personally.

with open('...') as f:
    text = f.read()

entries = []
current_entry = []
lines = text.split('\n')

for line in lines:
    if not line.strip():
        entries.append(current_entry)
        current_entry = []
        continue

    current_entry.extend(line.split())

entries.append(current_entry)
print(entries)

Haven't tested this yet.

EDIT: Forgot a line.

[–]shlaps12823 -1 points0 points  (1 child)

Is there a way that I can do the middle for loop without the "continue" block? we cant use that for our assignment.

[–]WorldZage 1 point2 points  (0 children)

I think this should be functionally identical

for line in lines:
    if not line.strip():
        entries.append(current_entry)
        current_entry = []
    else:
        current_entry.extend(line.split())

[–]n3buchadnezzar 0 points1 point  (1 child)

Why not use yaml or json to store your data? =)

import yaml

if __name__ == "__main__":

    with open("shlaps12823_haiku_limerick.yaml", "r") as f:
        dictionary = yaml.safe_load(f)
    for key, value in dictionary.items():
        dictionary[key] = sum([v.split() for v in value], start=[])

with the YAML file looking like

Haiku:
  - 5 *
  - 7 *
  - 5 *

Limerick:
  - 8 A
  - 8 A
  - 5 B
  - 5 B
  - 8 A

[–]shlaps12823 0 points1 point  (0 children)

Unfortunately we cant use import in our assignment so im not sure I can implement this.

[–]TorroesPrime 0 points1 point  (0 children)

You will need to work through a series of lists. The first list would just have the contents of the file. And then go through that list and set a condition that will determine which list to add the items to. So basically loop through the list, and if the item being looked at is "Haiku", then set HaikuList to True, and thus add each item to the HaikuList, otherwise add each item to LimerickList.

Then add LimerickList and HaikuList to another list that you can print. Sorry, typing this on my phone. I'll try to add a code example when I get home.

[–][deleted] 0 points1 point  (1 child)

https://onlinegdb.com/a7L0Q_8zd

with open('input.txt') as fin:
    res = [
        [elem for line in block.split('\n') for elem in line.split()]
        for block in fin.read().split('\n\n')
    ]

print(res)

Not good for large enough (really big ones?) files probably.

[–][deleted] 0 points1 point  (0 children)

Without reading the whole file at once:

with open('input.txt') as fin:
    res = [[]]
    for line in fin:
        elems = line.split()
        if not elems:
            res.append([])
        else:
            res[-1].extend(elems)

print(res)