我有一个循环函数,每次都返回一个复杂的嵌套字典,可以这样简化:
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可以创建一种清晰的显示数据的方式,如下所示:
所以我想在循环函数的末尾添加这样一个函数。我试过了
^{pr2}$我的问题是:我遇到了以下错误,我不知道如何将剪贴板上的数据保存到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
导出为类似excel格式的最简单方法是将
json
转换为pandas
数据帧,并将其导出为csv
。然后可以在电子表格中打开该文件错误说明你只能写入文件字符串对象,这里的文本变量是dictionary。Main this is write()只接受字符串对象。所以可以将dictionary对象转换为字符串
相关问题 更多 >
编程相关推荐