簡體   English   中英

如何將字典格式的txt文件轉換為python中的數據幀?

[英]How to convert a txt file with dictionary format to dataframe in 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

您可以嘗試使用不同的分隔符將文件讀取為 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
​

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM