【问题标题】:How to save complicated nested dictionary to clipboard and then to excel如何将复杂的嵌套字典保存到剪贴板,然后保存到 Excel
【发布时间】:2018-06-28 10:38:14
【问题描述】:

我有一个循环函数,每次返回一个复杂的嵌套字典,可以这样简化:

d= {
  "key1":"A", "key2":"B", "cumulative score":0.1, "direct score":0.4, "depth":0, 
  "chain":[
{"key1":"A1", "key2":"B1", "cumulative score":0.2, "direct score":0.5, "depth":1, 
  "chain":[{"key1":"A11", "key2":"B11","cumulative score":0.3, "direct score":0.6, "depth":2, "chain":[]}, 
         {"key1":"A12", "key2":"B12","cumulative score":0.5, "direct score":0.7, "depth":2, "chain":[]}]
},
{"key1":"A2", "key2":"B2","cumulative score":0.1, "direct score":0.2,"depth":1,
  "chain":[None, 
         {"key1":"A22", "key2":"B22","cumulative score":0.1, "direct score":0.5, "depth":2, "chain":[]}]
}
    ]

}

我的真实字典可以达到“深度”=10+,并且可以包含更多数据。由于我需要手动检查 excel 中的返回值,我发现将输出窗口复制到剪贴板,然后复制到 excel 可以创建一种清晰的方式来显示数据,如下所示:

所以我想在循环函数的末尾添加这样一个函数来执行此操作。这个我试过了

def add_to_clipboard(text):
import tempfile
with tempfile.NamedTemporaryFile("w") as fp:
    fp.write(text)
    fp.flush()
    command = "pbcopy < {}".format(fp.name)
    os.system(command)

我的问题是:我收到以下错误,我不知道将剪贴板上的数据保存到 Excel。 谁能帮忙?谢谢。

TypeError                                 Traceback (most recent call last)
<ipython-input-102-8afb2d14c221> in <module>()
----> 1 add_to_clipboard(result_test)

<ipython-input-101-89cb10853a94> in add_to_clipboard(text)
  2     import tempfile
  3     with tempfile.NamedTemporaryFile("w") as fp:
----> 4         fp.write(text)
  5         fp.flush()
  6         command = "pbcopy < {}".format(fp.name)

~\AppData\Local\Continuum\Miniconda3\envs\Battery\lib\tempfile.py in func_wrapper(*args, **kwargs)
481             @_functools.wraps(func)
482             def func_wrapper(*args, **kwargs):
--> 483                 return func(*args, **kwargs)
484             # Avoid closing the file as long as the wrapper is alive,
485             # see issue #18879.

TypeError: write() argument must be str, not dict

【问题讨论】:

    标签: python excel dictionary nested clipboard


    【解决方案1】:

    错误提示您只能写入文件中的字符串对象,这里的文本变量是字典。主要是 write() 只接受字符串对象。所以你可以将你的字典对象转换成字符串

    import json
    jsonStr = json.dumps(text)
    print(type(jsonStr ))
    fp.write(text)
    

    【讨论】:

    • 然后我收到错误“'Activity' 类型的对象不是 JSON 可序列化的”
    【解决方案2】:

    导出为类似 excel 格式的最简单方法是将您的 json 转换为 pandas 数据框并将其导出为 csv。然后您可以在电子表格中打开文件

    import pandas as pd
    
    out_file = 'my_file.csv'
    df = pd.DataFrame.from_dict(d, orient='index')
    df.to_csv(out_file)
    

    【讨论】:

    • 我知道 pandas 可以轻松写入 csv,但不幸的是,我的嵌套字典太复杂,无法写入表格。
    • 如果可以导出为Excel电子表格,那么应该也可以是DataFrame吧?您是否尝试过上面的代码,看看它是否有效?如果不是,您可以发布错误吗?
    • 我试了一下,发现可以导出数据到excel表格,但是格式不是我想要的(原帖图片是从剪贴板粘贴实现的)。由于我需要进行一些手动检查,一个单元格中的大量嵌套字典使我无法阅读和理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多