从文本中读取数据会变成行列表

时间:2018-03-11 13:59:54

标签: python

我在python中有一些数据作为数组,如下所示:

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")
]

我想从文件中读取这些数据。所以我创建了一个文本文件并将数据复制到其中。

现在,当我使用以下代码从文本文件中读取时:

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

train有8个项目由文本文档中的每一行分割。我希望它与我在python代码中提供的数据相同。请帮忙。提到的重复问题没有回答我的问题。

2 个答案:

答案 0 :(得分:0)

这应该有所帮助。使用ast模块

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

print(ast.literal_eval(train.replace("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')]

答案 1 :(得分:-1)

使用json库

# 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)