#πŸ”’ Reading a txt file and extracting data.

43 messages Β· Page 1 of 1 (latest)

chrome hamlet
#

So I've made a program that converts images to ASCII art.
And this program lets you load several images at the same time into a "session" I've now written a function that saves the currecnt "sesssion" to a .txt file.

But now I also want a function that can load such a .txt file and recreate the session. By extracting the data saves in it and running the appropriate functions.

Here is an example of what such a text files could look like:



-=Image Information=-
Name: 1
Filename: slalom.jpg
Size (Width x Height): 728 x 485
Target Size (Width x Height): 50 x 20
Brightness: 1.0
Contrast: 1.0

-=Image Information=-
Name: 2
Filename: slalom.jpg
Size (Width x Height): 728 x 485
Target Size (Width x Height): 50 x 20
Brightness: 1.0
Contrast: 1.0

-=Image Information=-
Name: kjdshfkjadshfkjdsf
Filename: slalom.jpg
Size (Width x Height): 728 x 485
Target Size (Width x Height): 50 x 20
Brightness: 1.0
Contrast: 1.0

================
Current image: kjdshfkjadshfkjdsf

This is what I want the function to do:

current_image.append(ImageProcessor(slalom.jpg))
current_image[-1].set_alias(name) if Name: is different than Filename:
current_image[-1].set_img_width(width) if Target size is different from 50 x *
current_image[-1].set_brightness(brightness) if Brightness: is different from 1.0
current_image[-1].set_contrast(contrast) if Contrast: is different from 1.0

I am having toruble writing a program that extracts the info...

twin pantherBOT
#

@chrome hamlet

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

umbral ore
chrome hamlet
#

THis is wha my currenct attempt at a function looks like

def load_session(file_path):
    all_images = []
    current_image = None

    with open(file_path, 'r') as file:
        lines = file.readlines()

    for line in lines:
        if line.startswith('-=Image Information=-'):
            if current_image:
                all_images.append(current_image)
            current_image = []
        elif line.startswith('================'):
            continue
        else:
            # Extracting image information
            key, value = map(str.strip, line.split(':', 1))
            if key == 'Target Size (Width x Height)':
                value = tuple(map(int, value.split('x')))
            elif key in ['Brightness', 'Contrast']:
                value = float(value)
            current_image.append((key, value))
               
    print(current_image)
    return current_image 
chrome hamlet
#

the class look like this:

class ImageProcessor:
    def __init__(self, filename):
        self.name = filename
        self.filename = filename
        self.width = 0
        self.height = 0
        self.brightness = 1.0
        self.contrast = 1.0
        self.target_width = 50
        self.target_height = int(50 / 1.65)
        self.data = None
        self.load_image()

    def load_image(self):
        try:
            self.data = Image.open(self.filename)
            self.width, self.height = self.data.size
            self.target_height = int(50 / 1.65 * (self.height / self.width))
            print(f"Image loaded: {self.filename}")
        except Exception as e:
            print(f"Error loading image: {e}")
            return None

    def set_alias(self, new_name):
        self.name = new_name
        print(f"Image name set to: {self.name}")

    def set_img_width(self, new_width):
        try:
            ratio = self.width / self.height
            self.target_width = new_width
            self.target_height = int(new_width / ratio / 1.65)
            print(f"Target witdh set to {new_width}, retaining aspect ratio.")
        except:
            print("Could not change the target width.")
    
    def set_img_height(self, new_height):
        try:
            ratio = self.width / self.height
            self.target_height = new_height
            self.target_width = int(new_height * ratio * 1.65)
            print(f"Target height set to {new_height}, retaining aspect ratio.")
        except:
            print("Could not change the target height.")

    def set_brightness(self, brightness):
        self.brightness = brightness
        
    def set_contrast(self, contrast):
        self.contrast = contrast
#

omitted some irrelevant stuff in the class

#

Does it makes sense?

#

the load function is supposed to return a list of objects

umbral ore
#

what do you get when you run the load_session() function?

chrome hamlet
#

Right now a "ValueError: not enough values to unpack (expected 2, got 1)"

#

on this line:

key, value = map(str.strip, line.split(':', 1))

umbral ore
#

yeah, do you see what line in the input file that gives you that error?

#

maybe the empty line?

chrome hamlet
#

I can't tell which line 😦

umbral ore
#

you can fix that with

for line_number, line in enumerate(lines):
    print(f"{line_number} {line}")
#

a small debugging aid πŸ˜‰

chrome hamlet
#

ah, thanks

#

I feel like I need to restart this process, xD

umbral ore
#

that for loop line is instead of your current for loop line and then just add that print line as the first line of the code block that you have in your for loop

chrome hamlet
#

oki

#

i think i solved the problem with the empty lines

#

Now i have another problem with runnign the correct functiosn from the data extracted

#

ah, nvm... it's not workign correctly

#

it only reads one object not multiple

umbral ore
#

oh, your returning current_image and not all_images from the function

#

and for debugging you probably want to print the right variable too

#

you should also remove the print statements from the function when your done debugging it

chrome hamlet
#

yeah, thanks, trying a bit on my own now and see if I can make it work correctly =S

umbral ore
#

and the enumerate thing, it will give you the line numbers counting from 0, not 1

#

so you might want to do it like print(f"{line_number+1} {line}") to get the correct line number printed

#

anyways, you're already done with that part of your debugging, so 🀷

chrome hamlet
#

Hmmmz, sorry i can't get anythign to work at the moment

#

I might rephase my question better and try again.

umbral ore
#

sure

chrome hamlet
#

GOnna split this into two questiosn and make it easer to understant and more clear

#

πŸ™‚

#

closeing this for now

#

.close

snow yarrowBOT
#
Did you mean:
chrome hamlet
#

!close

twin pantherBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.