擅长:python、mysql、java
<p>之所以会发生这种情况,是因为您试图将多维列表粘贴到单个csv单元格中。当这种情况发生时,csv模块不知道该做什么,所以它只是将条目作为字符串打印出来。要解决这个问题,您必须添加另一列并合并两个for循环。一个是词典键:值对另一个是字典值中的元组项。你知道吗</p>
<p>请尝试下面的示例脚本:</p>
<pre><code>with open("MYTESTER.csv", "wb") as f:
wcsv = csv.writer(f)
wcsv.writerow(['word', 'context', 'text'])
for key, value in dictionary.items():
for item in value:
wcsv.writerow([key, item[0], item[1]])
</code></pre>
<p>这将生成如下所示的csv文件:</p>
<pre><code>word, context, text
BatMan, 1.txt, I am Bat-Man
BatMan, 2.txt, Bat-man is awesome
Flash, 1.txt, The Flash is awesome
Flash, 1.txt, The Flash is only in txt 1 though
</code></pre>
<p>这本词典每行至少有三个条目,因此需要三列来存储它。你知道吗</p>