-1

I have some data in python as an array as follows :

train = [("Great place to be when you are in Bangalore.", "pos"),
  ("The place was being renovated when I visited so the seating was limited.", "neg"),
  ("Loved the ambience, loved the food", "pos"),
  ("The food is delicious but not over the top.", "neg"),
  ("Service - Little slow, probably because too many people.", "neg"),
  ("The place is not easy to locate", "neg"),
  ("Mushroom fried rice was spicy", "pos"),
  ("Cocee was hot and spicy", "neg")
]

I want to read this data from a file. So I created a text file and copied the data into it.

Now when I read from the text file using below code :

train = []
text_file = open("testdata.txt", "r")
train = text_file.readlines()
text_file.close()

the train is having 8 items splitted by each line in the text document. I want it as the same data I am giving in python code. Please help. The mentioned duplicate question did not answer mine.

ViVi
  • 4,339
  • 8
  • 29
  • 52

2 Answers2

0

This should help. Use the ast module

import ast
text_file = open("testdata.txt", "r")
train = text_file.read()
text_file.close()

print(ast.literal_eval(train.replace("train = ", "")))

Output:

[('Great place to be when you are in Bangalore.', 'pos'), ('The place was being renovated when I visited so the seating was limited.', 'neg'), ('Loved the ambience, loved the food', 'pos'), ('The food is delicious but not over the top.', 'neg'), ('Service - Little slow, probably because too many people.', 'neg'), ('The place is not easy to locate', 'neg'), ('Mushroom fried rice was spicy', 'pos'), ('Cocee was hot and spicy', 'neg')]
Rakesh
  • 81,458
  • 17
  • 76
  • 113
-1

use the json library

# reading
with open('dump.txt', 'r') as f:
    a = [tuple(x) for x in json.load(f)]

# writing
with open('dump.txt', 'w') as f:
    a = json.dump(f)
A.Bau
  • 82
  • 1
  • 10