简体   繁体   中英

python assign value of list variable from text file

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 ?

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))

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM