首页 > 解决方案 > Python 字典到 CSV 文件,但作为(键:值)分隔的行

问题描述

所以我创建了一个爬虫字典,而不是检查 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:value 的单独行:

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 语句来检查值是否存在。如果是,则打印将按“键,值”进行,如果没有,则打印将仅按“键”进行

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))

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

标签: pythonhtml

解决方案


采用str.join

前任:

[f.write('{0},{1}\n'.format(key, ",".join(value))) for key, value in dic.items()]

推荐阅读