如何在python中将字典格式的txt文件转换为数据帧?

2024-06-02 12:11:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含如下数据的文件:

{"cid": "ABCD", "text": "alphabets", "time": "1 week", "author": "xyz"}
{"cid": "EFGH", "text": "verb", "time": "2 week", "author": "aaa"}
{"cid": "IJKL", "text": "noun", "time": "3 days", "author": "nop"}

我希望阅读此文件并创建一个数据帧,如

cid     text    time    author
ABCD    alpha   1week   xyz
EFGH    verb    2week   aaa
IJKL    noun    3days   nop

Tags: 文件数据texttimenopauthornounweek
1条回答
网友
1楼 · 发布于 2024-06-02 12:11:10

您可以尝试使用不同的分隔符将文件读取为csv,并抓取第一列,然后应用ast.literal_eval转换为实际字典并转换回数据帧:

import ast
output = pd.DataFrame(pd.read_csv('file.txt',sep='|',header=None).iloc[:,0]
         .apply(ast.literal_eval).tolist())

print(output)

    cid       text    time author
0  ABCD  alphabets  1 week    xyz
1  EFGH       verb  2 week    aaa
2  IJKL       noun  3 days    nop

工作示例:

file = """{"cid": "ABCD", "text": "alphabets", "time": "1 week", "author":"xyz"}
{"cid": "EFGH", "text": "verb", "time": "2 week", "author": "aaa"}
{"cid": "IJKL", "text": "noun", "time": "3 days", "author": "nop"}"""

import io #dont need for reading a file directly , just for example
import ast
print(pd.DataFrame(pd.read_csv(io.StringIO(file),sep='|',header=None).iloc[:,0]
             .apply(ast.literal_eval).tolist()))

    cid       text    time author
0  ABCD  alphabets  1 week    xyz
1  EFGH       verb  2 week    aaa
2  IJKL       noun  3 days    nop
​

相关问题 更多 >