0

I am reading a line from the text file: The text file looks like this:

  2 [209:0.3720511,256:0.3525813,300:0.3466443,148:0.3456179,246:0.3443979,267:0.3425797,126:0.3397026,10:0.3379505,266:0.3357508,301:0.334953]

I am trying to convert [209:0.3720511,256:0.3525813,300:0.3466443,148:0.3456179,246:0.3443979,267:0.3425797,126:0.3397026,10:0.3379505,266:0.3357508,301:0.334953] in list containing values [209,256,300,148,246,267...]

I followed this link : Convert string representation of list to list

Here is my code but it's not working:

  with open("file.txt", "r") as text_file:
  for line in itertools.islice(text_file, 19, 20): # only one line
     print(ast.literal_eval(line.split("    ")[1]))

giving error.

Please help.

jpp
  • 134,728
  • 29
  • 196
  • 240
MAC
  • 788
  • 7
  • 26
  • 1
    `[209:0.3720511,256:0.3525813,300:0.3466443,148:0.3456179,246:0.3443979,267:0.3425797,126:0.3397026,10:0.3379505,266:0.3357508,301:0.334953]` is not a valid python list – Rakesh Sep 26 '18 at 10:46

2 Answers2

2

A colon is not part of a valid number in Python. Therefore, ast.literal_eval is inappropriate.

Instead, you can use a list comprehension combined with str.split and slicing:

x = '[209:0.3720511,256:0.3525813,300:0.3466443,148:0.3456179,246:0.3443979,267:0.3425797,126:0.3397026,10:0.3379505,266:0.3357508,301:0.334953]'

res = [int(i.split(':')[0]) for i in x[1:-1].split(',')]

# [209, 256, 300, 148, 246, 267, 126, 10, 266, 301]
jpp
  • 134,728
  • 29
  • 196
  • 240
0

If I take the exact string you have provided me:

  • split by space
  • take last item
  • replace problematic items [ ] with { }
  • do literal evaluation literal_eval = output python dict

    line_fixed = literal_eval(line.split(' ')[-1].replace('[', '{').replace(']', '}'))
    print (line_fixed.keys() )
    print (line_fixed.values() )
    
pajamas
  • 1,032
  • 1
  • 11
  • 23