Convert string-tuple to a tuple

2020-07-21 19:00发布

问题:

I have an input file with the following format:

[(1,1),(2,1)], 'add', 11
[(1,2),(1,3)], 'div', 2
[(3,1),(4,1),(3,2),(4,2)], 'times', 240
[(2,2),(2,3)], 'minus', 3
...

Each line is a tuple I want to create. How is it possible to convert each string line into a tuple?

For example, line string "[(1,1),(2,1)], 'add', 11" should be converted to a tuple: ([(1, 1), (2, 1)], 'add', 11).

So far, I tried:

tuples = []
for line in file:
    tuples.append((line,))

But I am getting a string conversion

 [("[(1,1),(2,1)], 'add', 11\n",), ("[(1,2),(1,3)], 'div', 2\n",), ("[(3,1),(4,1),(3,2),(4,2)], 'times', 240\n",), ("[(2,2),(2,3)], 'minus', 3",)]

回答1:

You may use ast.literal_eval as:

>>> import ast
>>> my_string = "[(1,1),(2,1)], 'add', 11"

>>> ast.literal_eval(my_string)
([(1, 1), (2, 1)], 'add', 11)

As per the ast.literal_eval(node_or_string) document:

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.