0

I have a text file with 10 arrays, 1 on each line. The code is supposed to take one of these arrays, and use each element to create an object from a class.

Here is the code:

class character(metaclass=ABCMeta):

    def __init__(self, name, lvl, hp,):
        self._name =  name
        self._lvl =  lvl
        self._hp = hp
        
    def stats(self):
        print("Name:", self._name)
        print("Level:", self._lvl)
        print("HP:", self._hp)

def venture():
    with open("Zone1.txt") as text:
        entries = text.readlines()
        search =(random.choice((entries))
        monster = character(search[0], search[1], search[2])

With the arrays in "Zone1.txt" looking like this:

["Fish", 5, 14]

Instead of pulling element 1, 2 & 3, it pulls the 1st, 2nd and 3rd character in the line.

Any help is appreciated and I will try to answer any question presented to me. I also wasn't sure how to properly describe my problem, and therefore couldn't find an existing question so apologies if dupe.

2
  • You are using the whole line to construct your arguments, you need to use the .split() method on them to split the lines in words, then your indexing will work as expected. Edit: I had not looked well enough, looks like you need to use json.loads(). Commented Jan 24, 2022 at 14:45
  • Do you have a typo in your "search" line? It should be search =(random.choice(entries)) Commented Jan 24, 2022 at 14:45

1 Answer 1

1

since you're reading from a text file, each line of the file is a string and not a list. you can convert this string into a list using a package called json:

import json


search =json.loads(random.choice(entries))
Sign up to request clarification or add additional context in comments.

3 Comments

It is now saying that monster = character(search[0], search[1], search[2]) has a syntax error, with "monster" highlighted
@OGComputerSci can you share the exact error? I'm running these lines and getting expected output, no errors. unless you didn't copy my exact line, since you had a typo in the search = ... line. you had a redundant (
Redid a couple lines and it worked, thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.