python help! invalid literal for int() with base 10:
Question: hi currently doing a code where the programe recalls two files one with
positions of words the other words the following code combines them however
when i change my code to be imported from a file i get the following error (if
compressed_sentence[(int(i)-1)]==uncompressed: ValueError: invalid literal for
int() with base 10: "['1',")

here is my code aswell:

    
    
    uncompressed = 0
    
    file1 = open ("NonDupT2.txt" , "r")
    compressed_sentence=file1.read()
    file1.close()
    
    file1 = open ("PositionT2.txt" , "r")
    compressed_Positionsonly=file1.read()
    file1.close()
    
    compressed_Positions= compressed_Positionsonly.split()
    
    print(str(compressed_Positions))
    
    for i in compressed_Positions:
        if compressed_sentence[(int(i)-1)]==uncompressed:    
            print(compressed_sentence[(int(i))])
            uncompressed = compressed_sentence[(int(i))]
    
        else:
            print(compressed_sentence[(int(i)-1)])
            uncompressed=compressed_sentence[(int(i)-1)]
    
        print(str(int(i)))
    

however it work when the variables are detemined by the program

    
    
    uncompressed = 0
    
    compressed_sentence = ['hello' , 'hello' , 'why' , 'hello' , 'lmao']
    compressed_Positions = ['1' , '1' , '2' , '1' , '3']
    
    print(str(compressed_Positions))
    
    for i in compressed_Positions:
    
        if compressed_sentence[(int(i)-1)]==uncompressed:    
            print(compressed_sentence[(int(i))])
            uncompressed = compressed_sentence[(int(i))]
    
        else:
            print(compressed_sentence[(int(i)-1)])
            uncompressed=compressed_sentence[(int(i)-1)]
    
        print(str(int(i)))
    


Answer: The issue is that the compressed_Positions are read wrongly. The file reads
the contents as one string. That string is the entire contents of the text
file.

The split operator makes a list of strings. The first element of that list is
everything from the file until the first space and that appears to be

    
    
    '[1,'
    

And that is what is interpreted by int() and that does not work. I think that
your PositionT2.txt contains:

    
    
    [1, 1, 2, 1, 3]
    

It works if it contained:

    
    
    1 1 2 1 3
    

To make the program work the same as the example with the explicit definition,
you need a split operator for compressed_sentences as well and your
NonDupT2.txt file must contain

    
    
    hello hello why hello lmao
    

Instead of spaces, you can also use line breaks as separators in your text
file.

Good luck, Joost

