Search code examples
pythonfileiostriparithmetic-expressions

Python- applying arithmetic to numbers in a text file without split


I'm working on take numbers in a text file and subtracting 255 from the number, but keeping the absolute value.

    def negate(char):
    '''
    absolute value of RGB value - 255
    '''
    line = int(char)
    negate_line = line - 255
    negate_line = abs(negate_line)
    negate_line = str(negate_line)
    return negate_line


`def process_body(infile, outfile, modification):`
    '''

    '''
    for line in infile.readlines():
        line = line.strip()
        for char in line:
            print(char, end="")
            # for debugging purposes. press enter to print next character in line
            input()


            if modification == "apply": 
                negate(line)
                outfile.write(negate)

I know I'm supposed to do something with string method in order to get the numbers by themselves, but I haven't been able to find a way to separate the numbers without using .split. The only string method aloud is .strip

The char in the negate function should be the value returned once I figure out a loop to separate the numbers in the text file, but I currently don't have a value because I have not figured out the loop yet.

The textfile looks like

0 44 89 0 44 89 0 44 89 0 44 89 1 45 90 
1 45 90 1 45 90 1 45 90 1 45 92 1 45 92 

Solution

  • def negate(num):
    '''
    absolute value of RGB value - 255
    '''
    line = int(num)
    negate_line = line - 255
    negate_line = abs(negate_line)
    negate_line = str(negate_line)
    return negate_line
    

    and

    def process_body(infile, outfile, modification):
    '''
    
    '''
    
    num = ""
    space = " "
    for line in infile.readlines():
        line = line.strip()
        s = line + space
        for char in line:
            print(char, end="")
            if char == space :
                num += s[num +1]
    
    
    
            # for debugging purposes. press enter to print next character in line
            input() 
    
            print(num, end="")
            # for debugging purposes. press enter to print next character in line
            input()
    
            if modification == "negate": 
                negate_line = negate(num)
                outfile.write(negate_line)
    
            if modification == "high contrast":
                hc = high_contrast(num)
                outfile.write(hc)
    

    My current output is 0

    0 4 04 4 044

    044 8 0448 9 04489

    But I need to be getting numbers like these

    255 211 166 255 211

    So this isn't quite an answer, but I'm not sure whats going wrong