簡體   English   中英

在Python中將字典格式的txt文件轉換為Excel

[英]Convert dictionary format txt file into excel in Python

對於txt文件result.txt ,如下所示:

[
  {
    "image_id": "42041",
    "mean_score_prediction": 4.996936075389385
  },
  {
    "image_id": "42039",
    "mean_score_prediction": 4.647608995437622
  },
  {
    "image_id": "42044",
    "mean_score_prediction": 3.9866196922957897
  },
  {
    "image_id": "42042",
    "mean_score_prediction": 3.9691513180732727
  },
  {
    "image_id": "42040",
    "mean_score_prediction": 4.303698152303696
  }
]

我想將其轉換為數據result.xlsx df然后另存為excel result.xlsx

print(df)
   image_id  mean_score_prediction
0     42041               4.996936
1     42039               4.647609
2     42044               3.986620
3     42042               3.969151
4     42040               4.303698

如何在Python中執行此操作? 謝謝。

首先,我使用Python讀取文件:

filename = 'result.txt'
with open(filename) as f:
    data = f.readlines()

print(data)

輸出:

['[\n', '  {\n', '    "image_id": "42041",\n', '    "mean_score_prediction": 4.996936075389385\n', '  },\n', '  {\n', '    "image_id": "42039",\n', '    "mean_score_prediction": 4.647608995437622\n', '  },\n', '  {\n', '    "image_id": "42044",\n', '    "mean_score_prediction": 3.9866196922957897\n', '  },\n', '  {\n', '    "image_id": "42042",\n', '    "mean_score_prediction": 3.9691513180732727\n', '  },\n', '  {\n', '    "image_id": "42040",\n', '    "mean_score_prediction": 4.303698152303696\n', '  }\n', ']\n']

采用:

In [1]: import pandas as pd

In [2]: with open("result.txt", 'r') as f:
   ...:     data = f.read()
   ...:

In [3]: data
Out[3]: '[\n  {\n    "image_id": "42041",\n    "mean_score_prediction": 4.996936075389385\n  },\n  {\n    "image_id": "42039",\n    "mean_score_prediction": 4.647608995437622\n  },\n  {\n    "image_id": "42044",\n    "mean_score_prediction": 3.9866196922957897\n  },\n  {\n    "image_id": "42042",\n    "mean_score_prediction": 3.9691513180732727\n  },\n  {\n    "image_id": "42040",\n    "mean_score_prediction": 4.303698152303696\n  }\n]'

In [6]: df = pd.read_json(data)

In [7]: df
Out[7]:
   image_id  mean_score_prediction
0     42041               4.996936
1     42039               4.647609
2     42044               3.986620
3     42042               3.969151
4     42040               4.303698

您的文本文件具有JSON格式,所以你可以使用read_json也如果沒有擴展.json

df = pd.read_json('result.txt')
print (df)
   image_id  mean_score_prediction
0     42041               4.996936
1     42039               4.647609
2     42044               3.986620
3     42042               3.969151
4     42040               4.303698

最后通過DataFrame.to_excel寫入excel:

df.to_excel('result.xlsx', index=False)

暫無
暫無

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

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