3 回答
TA贡献1880条经验 获得超4个赞
试试这个:
with open('test.csv', "a+", newline='', encoding="utf-8") as csv_file: writer = csv.writer(csv_file) writer.writerows(zip(original_final,replies_final))
TA贡献1890条经验 获得超9个赞
我对这个csv.writer()对象如何工作的实验是
writer.writerow([['a', 'b', 'c'], ['d', 'e', 'f']])生成 CSV 文件:
a, b, c
d, e, f
当你for item in original_final, replies_final在第一次迭代中有 then 时,items是一个列表等于original_final并且在第二次迭代中它是replies_final,所以它产生一个包含original_final然后的列replies_final
你想要的是第一次迭代, item 有两个元素:
[original_final[0], replies_final[0]]
在第二次迭代中,它应该是 [original_final[1], replies_final[1]]
等等
为此,您可以使用zip函数,如下所示
for item in zip(original_final, replies_final):
现在,您的下一个问题是original_final和replies_final需要具有相同的长度,否则该zip函数将根据两者中最短的一个来裁剪结果
所以你可以做的就是if像这样修改你的陈述
if 'replies' in i:
x = i['replies']['comments'][0]['snippet']['textOriginal']
replies_final.append(x)
else:
replies_final.append('')
我认为这应该有效
另外,有了with声明,你不需要做csv_file.close(). 你可以把它拿出来
所以这是最后的代码块
replies_final,original_final = [],[]
for i in data['items']:
original = i['snippet']['topLevelComment']['snippet']['textOriginal']
original_final.append(original)
if 'replies' in i:
x = i['replies']['comments'][0]['snippet']['textOriginal']
replies_final.append(x)
else:
replies_final.append('')
with open('test.csv',"a+", newline='',encoding="utf-8") as csv_file:
writer = csv.writer(csv_file)
for item in zip(original_final,replies_final):
writer.writerows([item])
TA贡献1773条经验 获得超3个赞
您需要考虑各种事情,例如,如果您的项目包含多个回复,您可以将它们全部存储到一个临时数组中,稍后您可以将其附加到您的replies_final对象,如果它不包含任何回复,它将保持为空,您仍然已经用与每个项目的 1:1 关系填充你的 replies_final 数组,即使它是空的
for i in data['items']:
original = i['snippet']['topLevelComment']['snippet']['textOriginal']
original_final.append(original)
item_replies = []
if 'replies' in i:
# Here you can iterate over the replies and add them to a temp array
for reply in i['replies']:
x = i['replies']['comments'][0]['snippet']['textOriginal']
item_replies.append(x)
replies_final.append(item_replies)
然后你可以使用 zip 函数获取两个数组并将它们变成一个你可以迭代的对象,这很好,因为你已经知道对于每个项目你已经有一个评论列表,即使它是空的信息也会现在混合。然后你调用了错误的函数而不是使用writerows()你必须使用writerow()一次插入一个
with open('test.csv',"a+", newline='',encoding="utf-8") as csv_file:
writer = csv.writer(csv_file)
for i in zip(arr,arr2):
(item, replies) = i
writer.writerow([item, replies]))
csv_file.close(
```
添加回答
举报