python - 写入输出 CSV 格式错误/奇怪
问题描述
我正在做 Web Scraping - 我有一个包含大约 140 个页面标题的列表,但是在将其写入 CSV 之后,标题的格式变得非常奇怪。在使用 Spyder 的 Python 中,我可以看到正确的结果,但只有在编写之后,在 CSV 中它变得很奇怪。
这是我写的代码。我在这里做错什么了吗?
o_file = open('headlines.csv','w')
with o_file:
writer = csv.writer(o_file, delimiter=' ', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
writer.writerows(h_list)
CSV 中的输出如下所示(每个字母后有空格,每个单词后有引号):
H e r e ' s " " W h y " " T h e r e " " W a s " " a n " " E m p t y " " S e a t " " N e x t " " t o " " P r i n c e " " W i l l i a m " " a t " " t h e " " R o y a l " " W e d d i n g
此外,在某些行的 CSV 中,第二列中也有数据。虽然我正在做的工作有一个包含 140 个页面标题的列表,我可以在 Spyder 中看到它,但它是如何以及为什么在第二列中也给出一些页面标题?有什么想法吗?
解决方案
我不明白为什么你还没有提供我(和其他人)要求的额外信息,所以以下充其量只是一个有根据的猜测——它实现了我在我的一个评论中向你提出的建议(即转换h_list
为包含单个字符串的列表列表):
import csv
h_list = [
"Here's Why There Was an Empty Seat Next to Prince William at the Royal Wedding",
"NASA wrestles with what to do with International Space Station after 2024",
"Father-son team pilot plane from Seattle to Amsterdam",
# etc...
]
with open('headlines.csv', 'w', newline='') as o_file:
writer = csv.writer(o_file)
# Make each line in h_list a row with a single headline string in it.
writer.writerows([headline] for headline in h_list)
print('done')
执行后的内容headlines.csv
:
Here's Why There Was an Empty Seat Next to Prince William at the Royal Wedding
NASA wrestles with what to do with International Space Station after 2024
Father-son team pilot plane from Seattle to Amsterdam
我不确定这是否是您在csv
文件中想要的 - 因为当每行中只有一个值(字段)时使用该格式并没有多大意义(因此不需要分隔符) - 但是,如果仅此而已,也许它会帮助您找出正确的做法。
推荐阅读
- apache-flink - Flink:单独运行 sinks
- python - 如何在 Heroku 或类似设备上快速部署 Aiohttp Python 项目
- r - 在ggplot2中向图例添加简单的直方图
- javascript - Phaser 3 为玩家创建类
- konvajs - 尝试从 JSON 加载阶段时出现“未捕获的类型错误:无法设置未定义的属性‘容器’”
- flask - 部署在 heroku 上的 Flask 应用程序具有变量,有时在更新后会恢复到以前的状态
- c# - ASP.NET Web 应用程序中的外部连接
- flutter - Flutter Flatbutton onpressend不起作用
- html - 有没有办法递归地选择一个班级的所有孩子到另一个班级
- javascript - 页面上带有光滑滑块的奇怪空间?