python - 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))
然后我想写一个循环遍历每一行并检查括号并删除它们。是的,我知道我可能写错了,所以我很高兴知道我的错误在哪里。谢谢。
解决方案
采用str.join
前任:
[f.write('{0},{1}\n'.format(key, ",".join(value))) for key, value in dic.items()]
推荐阅读
- java - 为 Swing 应用程序选择哪个 LayoutManager?
- python - 如何并排组合一个numpy数组和一个熊猫系列并返回匹配的行数
- python - Choropleth 地图 geopandas
- typescript - 如何使用 babel 7 和 TypeScript 3.7 运行 mocha 6?
- java - 如何将序列化对象写入资源文件
- javascript - 根据对象数组中的键创建对象
- python - 0 False 和所有其他整数值 True 吗?
- javascript - 如何将一组坐标映射到 React Native Maps Markers?
- c# - “忘记电子邮件”功能不发送电子邮件
- c# - c# Binary Reader System.InvalidCastException: