Reputation: 51
[0, 1, 2, 3],[4, 5, 6, 7, 8],[9, 10, 11],[12, 13, 14, 15],[16, 17, 18, 19, 20],[21, 22, 23]
[0, 1, 2],[3, 4, 5],[6, 7, 8, 9],[10, 11, 12, 13]
[0, 1],[2],[3, 4, 5],[6, 7, 8, 9]
[0, 1, 2, 3],[4, 5, 6, 7],[8],[9, 10, 11, 12],[13, 14, 15]
I have the above text file. The problem is that each of the indexes in this file are a string but I want to convert them back to integers. I tried this:
with open("abc.txt", "r") as text_file:
new_list = [int(line) for line in text_file]
I got this error:
ValueError: invalid literal for int() with base 10: '[0, 1, 2, 3],[4, 5, 6, 7, 8],[9, 10, 11],[12, 13, 14, 15],[16, 17, 18, 19, 20],[21, 22, 23]\n'
Output-
[0, 1, 2, 3],[4, 5, 6, 7, 8],[9, 10, 11],[12, 13, 14, 15],[16, 17, 18, 19, 20],[21, 22, 23]
[0, 1, 2],[3, 4, 5],[6, 7, 8, 9],[10, 11, 12, 13]
[0, 1],[2],[3, 4, 5],[6, 7, 8, 9]
[0, 1, 2, 3],[4, 5, 6, 7],[8],[9, 10, 11, 12],[13, 14, 15]
Just that all these lines represent lists containing INTEGERS.
Upvotes: 2
Views: 89
Reputation: 5785
Read about ast.literal_eval
Try this,
import ast
with open("abc.txt", "r") as text_file:
new_list = [list(ast.literal_eval(line)) for line in text_file if line.strip()]
Output:
[[[0, 1, 2, 3], [4, 5, 6, 7, 8], [9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23]],
[[0, 1, 2], [3, 4, 5], [6, 7, 8, 9], [10, 11, 12, 13]],
[[0, 1], [2], [3, 4, 5], [6, 7, 8, 9]],
[[0, 1, 2, 3], [4, 5, 6, 7], [8], [9, 10, 11, 12], [13, 14, 15]]]
Upvotes: 3
Reputation: 1265
You can use literal_eval
and chain
:
from ast import literal_eval
from itertools import chain
with open("abc.txt", "r") as text_file:
new_lines = (list(literal_eval(line)) for line in text_file if line.strip())
new_list = list(chain(*new_lines))
line.strip()
is to skip empty line.
Upvotes: 2
Reputation: 23
Regex is your best bet once you've read the data like that,
z = re.findall("[\d]+",your_string)
Then what's left is to convert each string in the list to an integer, here's a straightforward example,
for i in range(len(z)):
new_z[i] = int(z[i])
Upvotes: 2