Home > Net >  How do I split a list created from a .txt file with elements separated by "/"?
How do I split a list created from a .txt file with elements separated by "/"?

Time:11-11

This is my function:

def read_file():
    textfile = open("Animals.txt", "r", encoding="utf-8")
    list = textfile.readlines()
    print(list)
    textfile.close()

This is Animals.txt:

Animal / Hibernation / Waking Hours / Feeding Time

Bear / winter / 9-20 / 12

Nightowl / - / 21-05 / 21

Sealion / - / 6-18 / 14

How do make a list where the information on each line relates to the animal Name. For example I would like Bear to be connected with winter, 9-20, 12 and also be separated from Nightowl.

My first idea was to separate the list with .split and then moving forward using the list index to navigate the elements. Just printing the list gave this:

['Bear / winter / 9-20 / 12\n', 'Nightowl / - / 21-05 / 21\n', 'Sealion / - / 6-18 / 14 \n', 'Seal / - / 6-18 / 14\n', 'Wolf / - / 6-20 / 12\n', 'Moose / - / 7-19 / 10\n']

  1. How do I split the list so that everything is its own element?
  2. Is it better to use a dictionary and if so how do I make a dictionary where the Name i.e Bear correlates to all the other elements?

CodePudding user response:

The file format is essentially CSV (albeit that the separators are not commas). You could use pandas or the csv module but as this so trivial I suggest:

class Animal:
    def __init__(self, animal, hibernation, waking_hours, feeding_time):
        self._animal = animal
        self._hibernation = hibernation
        self._waking_hours = waking_hours
        self._feeding_time = feeding_time
    def __str__(self):
        return f'Animal={self._animal}, Hibernation={self._hibernation}, Waking hours={self._waking_hours}, Feeding time={self._feeding_time}'

list_of_animals = []

with open('Animals.txt') as afile:
    for line in afile.readlines()[1:]:
        list_of_animals.append(Animal(*map(str.strip, line.split('/'))))

print(*list_of_animals, sep='\n')

Output:

Animal=Bear, Hibernation=winter, Waking hours=9-20, Feeding time=12
Animal=Nightowl, Hibernation=-, Waking hours=21-05, Feeding time=21
Animal=Sealion, Hibernation=-, Waking hours=6-18, Feeding time=14
Animal=Seal, Hibernation=-, Waking hours=6-18, Feeding time=14
Animal=Wolf, Hibernation=-, Waking hours=6-20, Feeding time=12
Animal=Moose, Hibernation=-, Waking hours=7-19, Feeding time=10

CodePudding user response:

You can use pandas and the read_csv-function with the slash being defined as the separator.

  • Related