首页 > 解决方案 > 写入输出 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 中看到它,但它是如何以及为什么在第二列中也给出一些页面标题?有什么想法吗?

标签: pythonweb-scraping

解决方案


我不明白为什么你没有提供我(和其他人)要求的额外信息,所以以下充其量只是一个有根据的猜测——它实现了我在我的一个评论中向你提出的建议(即转换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文件中想要的 - 因为当每行中只有一个值(字段)时使用该格式并没有多大意义(因此不需要分隔符) - 但是,如果仅此而已,也许它会帮助您找出正确的做法。


推荐阅读