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

2024-04-25 05:03:12 发布

您现在位置: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代码中给出的数据相同。请帮忙。刚才提到的问题没有回答我的问题


Tags: theto数据textposfoodisnot
2条回答

使用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)

这应该会有帮助。使用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')]

相关问题 更多 >