在scrapy python中的一行csv文件中每列排列一个项目

时间:2012-05-30 12:24:49

标签: python csv dictionary scrapy pipeline

我从一个网站上删除了一些项目,我将它们放入json文件中,如下所示

{
 "author": ["TIM ROCK"], 
 "book_name": ["Truk Lagoon, Pohnpei & Kosrae Dive Guide"], 
 "category": "Travel", 
}
{
 "author": ["JOY"], 
 "book_name": ["PARSER"], 
 "category": "Accomp", 
}

我想将它们存储在csv文件中,每行一个字典,每列一个项目如下所示

|    author   |     book_name     |    category   |
|   TIM ROCK  |  Truk Lagoon ...  |     Travel    |
|     JOY     |   PARSER          |     Accomp    |

我在一行中获取一个字典的项目,但所有列合并

我的pipeline.py代码是

导入csv

class Blurb2Pipeline(object):

    def __init__(self):
        self.brandCategoryCsv = csv.writer(open('blurb.csv', 'wb'))
        self.brandCategoryCsv.writerow(['book_name', 'author','category'])

    def process_item(self, item, spider):
        self.brandCategoryCsv.writerow([item['book_name'].encode('utf-8'),
                                    item['author'].encode('utf-8'),
                                    item['category'].encode('utf-8'),
                                     ])
        return item        

1 个答案:

答案 0 :(得分:1)

要点是csv.DictWriter

非常简单
>>> inputs = [{
...  "author": ["TIM ROCK"], 
...  "book_name": ["Truk Lagoon, Pohnpei & Kosrae Dive Guide"], 
...  "category": "Travel", 
... },
... {
...  "author": ["JOY"], 
...  "book_name": ["PARSER"], 
...  "category": "Accomp", 
... }
... ]
>>> 
>>> from csv import DictWriter
>>> from cStringIO import StringIO
>>> 
>>> buf=StringIO()
>>> c=DictWriter(buf, fieldnames=['author', 'book_name', 'category'])
>>> c.writeheader()
>>> c.writerows(inputs)
>>> print buf.getvalue()
author,book_name,category
['TIM ROCK'],"['Truk Lagoon, Pohnpei & Kosrae Dive Guide']",Travel
['JOY'],['PARSER'],Accomp

最好将这些数组加入到某些内容中,但由于元素可以是列表或字符串,因此它有点棘手。如果某些东西是字符串或某些其他可迭代的东西,则是Python中为数不多的直接类型检查很有意义的案例之一。

>>> for row in inputs:
...     for k, v in row.iteritems():
...         if not isinstance(v, basestring):
...             try:
...                 row[k] = ', '.join(v)
...             except TypeError:
...                 pass
...     c.writerow(row)
... 
>>> print buf.getvalue()
author,book_name,category
TIM ROCK,"Truk Lagoon, Pohnpei & Kosrae Dive Guide",Travel
JOY,PARSER,Accomp