繁体   English   中英

使用python编写csv时创建新标题

[英]Create new headers when writing a csv using python

我在网上抓取不同的网页,对于每个网页,我正在编写 csv 文件的每一行

import csv
fieldnames=["Title", "Author", "year"]
counter=1
for webpage of webpages:
    if counter==1:
        f = open('file.csv', 'wb')  
        my_writer = csv.DictWriter(f, fieldnames)
        my_writer.writeheader()
        f.close()

    something where I get the information (title, author and year) for each webpage

    variables={ele:"NA" for ele in fieldnames}
    variables['Title']=title        
    variables['Author']=author
    variables['year']=year


    with open('file.csv', 'a+b') as f:
    header = next(csv.reader(f))
    dict_writer = csv.DictWriter(f, header)
    dict_writer.writerow(variables) 
    counter+=1

但是,可能有多个作者(因此网络抓取后的作者实际上是一个列表)所以我想在 csv 文件的标题中包含:author1、author2、author3 等。但我不知道会是什么是作者的最大数量。 因此,在循环中,我想编辑标题并开始添加 author2、author3 等,具体取决于该行中是否需要创建更多作者。

它可能是这样的:

def write_to_csv(file_name, records, fieldnames=None):

    import csv
    from datetime import datetime

    with open('/tmp/' + file_name, 'w') as csvfile:
        if not fieldnames:
            fieldnames = records[0].keys()
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames,   extrasaction='ignore')
        writer.writeheader()
        for row in records:
            writer.writerow(row)

def scrape():
    for webpage of webpages:
        webpage_data = [{'title':'','author1':'foo','author2':'bar'}] #sample data
        write_to_csv(webpage[0].title+'csv', webpage_data,webpage_data[0].keys())

我假设:

  • 同一个网页的数据会一致,但循环中的下一个网页不同
  • 网页数据是字典列表,将值映射到键
  • 上面的代码基于 Python 3

所以在循环中,我们只需要获取数据,然后将相关的字段名和值传递给另一个函数,这样就可以将其写入 csv。

因为“作者”是一个可变长度的列表,您应该以某种方式将它序列化以适合单个字段。 例如,使用分号作为分隔符。

假设您有一个authors字段,其中包含来自您的webpage对象的所有作者,您可能希望将分配行更改为如下所示:

variables['Authors']=';'.join(webpage.authors)

这是所有作者的简单序列化。 您当然可以想出其他方法 - 使用不同的分隔符或序列化为 JSON 或 YAML 或类似的更复杂的东西。

希望这能提供一些想法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM