Python: How to split text into multidimensional array

I’m grabbing data from a web-page and finally have 5 strings which look like this:

  charts[1]['min']    = [['Mi',5.6],['Do',2.9],['Fr',1.7],['Sa',3.7],['So',2.9],['Mo',4.1],['Di',4]];
  charts[1]['mittel'] = [['Mi',6.2],['Do',5.4],['Fr',3.9],['Sa',4.5],['So',4.7],['Mo',5.4],['Di',4.6]];
  charts[1]['max']    = [['Mi',7.2],['Do',8.8],['Fr',5.9],['Sa',5.5],['So',6.8],['Mo',6.6],['Di',5.8]];
  charts[2]['line']   = [['Mi',59],['Do',69],['Fr',72],['Sa',65],['So',66],['Mo',65],['Di',76]];
  charts[3]['line']   = [['Mi',5],['Do',4],['Fr',0],['Sa',5],['So',0],['Mo',5],['Di',0]];

Obviously I would need an array containing only the right part. Data is always a day (in German) and a number. New to Python I look for an easy solution. Any ideas?

>Solution :


import ast

str1 = "charts[1]['min']    = [['Mi',5.6],['Do',2.9],['Fr',1.7],['Sa',3.7],['So',2.9],['Mo',4.1],['Di',4]];"

arr1 = ast.literal_eval(str1.split('=')[1].strip()[:-1])

# Output:
[['Mi', 5.6],
 ['Do', 2.9],
 ['Fr', 1.7],
 ['Sa', 3.7],
 ['So', 2.9],
 ['Mo', 4.1],
 ['Di', 4]]

Leave a Reply