1

我有从网站上抓取的项目,我将它们放入如下的 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        
4

1 回答 1

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

最好将这些数组加入某些东西,但由于元素可以是 list 或string,所以有点棘手。判断某事物是字符串还是其他可迭代对象是 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
于 2012-05-30T12:36:00.563 回答