0

I have Following data in txt file. need to load this data in Python list.

[('Get RC for Apple for SmallCA for CAR?', {'entities': [ (11, 16, 'ORG'),(4, 6, 'Revenue'),(21, 28, 'Product'),(33, 36, 'Region')]}),('Get REVCCR for Apple for SmallCA for CAR?', {'entities': [ (15, 20, 'ORG'),(4, 10, 'REV'),(25, 32, 'Product'),(37, 40, 'CAA')]})]

1) I have open this file and read all the data, but its loaded as string.
2) Try to load using numpy but its not getting loaded as expected

data = set(w.rstrip() for w in open('../File/DataList.txt'))
print(data )

Should load data as below

data = [('Get RC for Apple for SmallCA for CAR?', {'entities': [ (11, 16, 'ORG'),(4, 6, 'Revenue'),(21, 28, 'Product'),(33, 36, 'Region')]}),('Get REVCCR for Apple for SmallCA for CAR?', {'entities': [ (15, 20, 'ORG'),(4, 10, 'REV'),(25, 32, 'Product'),(37, 40, 'CAA')]})]
print(data)
davedwards
  • 7,011
  • 2
  • 15
  • 45

2 Answers2

1

Use ast.literal_eval():

import ast

with open('../File/DataList.txt', 'r') as f:
    data = ast.literal_eval(f.read())

>>> print(data)
[('Get RC for Apple for SmallCA for CAR?', {'entities': [(11, 16, 'ORG'), (4, 6, 'Revenue'), (21, 28, 'Product'), (33, 36, 'Region')]}), ('Get REVCCR for Apple for SmallCA for CAR?', {'entities': [(15, 20, 'ORG'), (4, 10, 'REV'), (25, 32, 'Product'), (37, 40, 'CAA')]})]

Confirm it is a python list:

>>> type(data)
<class 'list'>
davedwards
  • 7,011
  • 2
  • 15
  • 45
0

You could try and use the json module to do this:

import json

with open("../File/DataList.txt", 'r') as f:
    data = json.load(f)

This works by reading the file as JSON data. As the data is in the form of a list, it will store it as a list. You can use the same method to save object data into a file as well. It doesn't matter that the file extension isn't .json, as it only cares about the contents of the file.

I hope that this helps :)