0

I am trying to read a text file and I want to convert the below string to a 2d array.

File Data:

[[],['java','j2ee','spring'],['.net','c#','mysql'],['php','mysql']] 

My Code:

with open("test.txt") as myfile:
    sentences = np.array(myfile.readline(),dtype=object)

print(sentences)

It returns the below array

array("[[],['java','j2ee','spring'],['.net','c#','mysql'],['php','mysql']]", dtype=object)

I want following output

array([[],['java','j2ee','spring'],['.net','c#','mysql'],['php','mysql']],dtype=object)
John Smith
  • 322
  • 3
  • 13

1 Answers1

-1

You could use sentences=np.array(eval(sentences[0])) Warning: as mentioned in the comments, eval can pose a security risk. Use with caution.

John Smith
  • 322
  • 3
  • 13
  • Why the down vote? – John Smith Aug 17 '20 at 19:25
  • 1
    I can only guess, but maybe because "code only" answers (sorry I don't count the 3 additional words) are not really appreciated on SO. And some people downvote answers on questions that should be closed. This question is a duplicate, meaning there already good answers available. Repeating it here is not really useful. Hope this helps. – wovano Aug 17 '20 at 19:39
  • 1
    FYI: It's also flagged as Low Quality Post, where it's currently being reviewed. It might help to read [How do I write a good answer](https://stackoverflow.com/help/how-to-answer) – wovano Aug 17 '20 at 19:41
  • 1
    By the way, `eval()` is considered bad, since it is an unsafe function (security risk). Especially when using it on external data, such as data read from a file. You should really warn about that if you advice someone to use it. – wovano Aug 17 '20 at 20:37