回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我有一个循环函数,每次都返回一个复杂的嵌套字典,可以这样简化:</p>
<pre><code>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":[]}]
}
]
</code></pre>
<p>}</p>
<p>我真正的字典可以达到“深度”=10+,并且可以有更多的数据。由于我需要在excel中手动检查返回值,我发现将输出窗口复制到剪贴板,然后复制到excel可以创建一种清晰的显示数据的方式,如下所示:</p>
<p><a href="https://i.stack.imgur.com/ZlkRZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZlkRZ.jpg" alt="enter image description here"/></a></p>
<p>所以我想在循环函数的末尾添加这样一个函数。我试过了</p>
^{pr2}$
<p><strong>我的问题是:我遇到了以下错误,我不知道如何将剪贴板上的数据保存到excel。</strong>有人能帮忙吗?谢谢。在</p>
<pre><code>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
</code></pre>