1

I have a text file named datapolygon.txt, containing:

    Polygon In
    [(2,0),(3,0),(3,-2),(2,-2)]
    [(3,0),(4,0),(4,-2),(3,-2)]
    

I want to assign that text value to a two dimensional list (list of lists). the result should be something like this :

    polygonIn = [[(2,0),(3,0),(3,-2),(2,-2)],[(3,0),(4,0),(4,-2),(3,-2)]]
    
is there any simple way to achieve that other than to get through some complicated loop and check every substring and index then convert it to int and make it a tuple then assign it to variable polygonIn one by one using nested loops ?

0

3 Answers 3

4

You can use ast.literal_eval() to convert your string to a list:

>>> import ast
>>> s = '[(2,0),(3,0),(3,-2),(2,-2)]'
>>> print(ast.literal_eval(s))
[(2, 0), (3, 0), (3, -2), (2, -2)]

and you can simply append to an empty list. Here is an example:

import ast
polygon_in = []
with open('polygon.txt', 'r') as f:
    polygon_str = f.readline()
    polygon_in.append(ast.literal_eval(polygon_str))
Sign up to request clarification or add additional context in comments.

Comments

4

Assuming you can ensure that your line is a valid list of tuples (or some other valid data type), you can use

import ast
ast.literal_eval(line)

where line is the line you've read from your file.

If you know that you have lists of tuples and labels as you showed in your example, you could use a regular expression like ^\[([\(\-[0-9],)\s]*\] to ensure it is one of the data lines.

Comments

0

Piggy-backing on Selcuk's answer:

import ast
def processFile (filename):
    theFile = open(filename, 'r')
    finalList = []
    for aLine in theFile:
        try:
            finalList.append(ast.literal_eval(aLine))
        except:
            useless = True
    return finalList

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.