我热衷于使用项目加载器,在示例中使用像mapcompose这样的加载器处理器来清理文本,例如:
clean_text = Compose(MapCompose(lambda v: v.strip()), Join())
test = ['item1', 'item2', 'item3']
clean_text(test)
它返回:
u'item1 item2 item3'
现在,我想要一个不同的输出,对于相同的输入,我需要用逗号分隔的数据,并且由于我正在使用.csv文件,所以我也引用了文本以免破坏格式。
'"""item1,item2,item3"""'
为此,我编写了此函数:
def quote_field(text):
text = ','.join([v.strip() for v in text ])
return '"""' + text.strip() + '"""'
如何实现项目加载器?
你离得很近。 首先,您应该了解Compose
和MapCompose
类。Compose
用于将某些函数应用于项目列表,而MapCompose
用于对项目列表中的每个项目应用某些函数。
所以你想要:
from scrapy.loader.processors import MapCompose, Compose, Join
clean_text = Compose(
MapCompose(str.strip), # strip every item in list
MapCompose(lambda item: f'"{item}"'), # wrap every value in quotes
Join(','), # join all items in list as one using , as separator
)
如果您对其进行测试:
test = ['item1', 'item2', 'item3']
clean_text(test)
#'item1,item2,item3'