gpt4 book ai didi

Python 字典到 CSV 文件,但作为(键 :value) seperated lines

转载 作者:太空宇宙 更新时间:2023-11-03 19:50:18 25 4
gpt4 key购买 nike

因此,我创建了一个爬虫字典,用于检查 html 文件并查找针对其他 html 文件的“href=”短语。

所以字典看起来像这样:

{'1.html': ['2.html', '3.html'], '2.html': ['3.html', '4.html'], '3.html': ['5.html', '7.html'], '5.html': [], '7.html': ['2.html'], '4.html': ['6.html'], '6.html': ['2.html']}

我想从这本词典创建一个 CSV 文件。我希望通过这种设计将每个键组织为单独的行:值:

key,value1a,value1b
key2,value2a,value2b

例如:

1.html,2.html,3.html
2.html,3.html,4.html
and etc

所以这应该很容易,我确实设法创建了一个如下所示的 csv 文件:

> 1.html,['2.html', '3.html']
> 2.html,['3.html', '4.html']
> 3.html,['5.html', '7.html']
> 5.html,[]
> 7.html,['2.html']
> 4.html,['6.html']
> 6.html,['2.html']

使用代码:

with open('my_file.csv', 'w') as f:
[f.write('{0},{1}\n'.format(key, value)) for key, value in dic.items()]

但现在我必须删除括号和键后的“,”,而不附加任何值(例如:5.html)。

所以我考虑制作一个 if 语句来检查该值是否存在。如果是,则打印将按“键,值”进行如果没有,打印将仅通过“key”进行

This is my code:
with open('file.csv', 'w') as f:
for key, value in dic.items:
if value:
f.write('{0},{1}\n'.format(key, value))
else:
f.write('{0}\n'.format(key))

然后我想编写一个循环来遍历每一行并检查括号并将其删除。是的,我知道我可能写错了,所以我很高兴知道我的错误在哪里。谢谢。

最佳答案

使用带有 key 的加入命令,如下所示:

with open('file.csv', 'w') as f: 
for key, value in dic.items:
if value:
f.write('{0},{1}\n'.format(key, ",".join(value)))
else:
f.write('{0}\n'.format(key))

关于Python 字典到 CSV 文件,但作为(键 :value) seperated lines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59879987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com