简体   繁体   English

在 scrapy csv 文件中保留前导零

[英]Preserve leading zeros in scrapy csv file

I need to preserve the leading zeros while exporting zip codes to the csv file in scrapy.在将 zip 代码导出到 scrapy 中的 csv 文件时,我需要保留前导零。 I have the following exporter to implement but it didn't help me.我有以下出口商要实施,但它对我没有帮助。

import csv

from scrapy.exporters import CsvItemExporter


class QuoteAllDialect(csv.excel):
    quoting = csv.QUOTE_ALL


class QuoteAllCsvItemExporter(CsvItemExporter):

    def __init__(self, *args, **kwargs):
        kwargs.update({'dialect': QuoteAllDialect})
        super(QuoteAllCsvItemExporter, self).__init__(*args, **kwargs)

I extract zip codes in the following way.我通过以下方式提取 zip 代码。 In this way they are never treated as integers:通过这种方式,它们永远不会被视为整数:

addr = response.xpath('//address/span/text()').extract()

full_ad = ", ".join(addr)

zip_code = full_ad[-5:]

I need help in finding out the way to implement so that scrapy handles it automatically.我需要帮助找出实现方法,以便 scrapy 自动处理它。 Any help would be appreciated.任何帮助,将不胜感激。 Thanks谢谢

I need to preserve the leading zeros while exporting zip codes我需要在导出 zip 代码时保留前导零

It sounds like you are treating zip codes as integers.听起来您将 zip 代码视为整数。 Don't do that;不要那样做; just treat them as strings.只需将它们视为字符串。 They have no integer meaning (you can't do any reasonable arithmetic on them), so don't interpret them as integers.它们没有 integer 含义(您无法对它们进行任何合理的算术运算),因此不要将它们解释为整数。

Then you won't have to worry about preserving any formatting.这样您就不必担心保留任何格式。

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

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