【问题标题】:Parsing CVS with unique formatting用独特的格式解析 CVS
【发布时间】:2017-06-24 15:35:14
【问题描述】:

我有一个类别、品牌和产品列表的 PDF 输出。但是,该列表不可搜索。 PDF 的 CSV 对话使输出看起来像这样:

“猫 1”

“品牌 1”

“产品 1”

“产品 2”

“品牌 2”

“产品 3”

“产品 4”

“猫 2”

在大多数情况下,我可以确定哪个是类别、品牌或产品。品牌没有任何具体信息,但类别有 (#/#) 标签,产品上有日期。

我想知道如何使用 ruby​​ 的 CSV 类将它变成这样的东西,以便它更易于搜索。

“类别 1”“品牌 1”“产品 1”

“类别 1”“品牌 1”“产品 2”

“类别 1”“品牌 2”“产品 3”

“类别 1”“品牌 2”“产品 4”

【问题讨论】:

    标签: ruby csv


    【解决方案1】:

    你可以

    new_csv = 'Category,Brand,Product\n'
    cat = ''
    brand = ''
    product = ''
    regexp_cat = Regexp.new YOUR_REGEX_TO_IDENTIFY_TAG
    regexp_prod = Regexp.new YOUR_REGEX_TO_IDENTIFY_DATE
    
    File.foreach( 'file.txt' ) do |line|
    
      if line =~ regexp_cat
        cat = line
        # if the line is a category you'll want to move to the next without writing to "new_csv", until you find a product
        next
    
      elsif line =~ regexp_prod
        product = line
    
      else
        brand = line
        # same if the line is a brand you'll want to move to the next item until you find a product
        next
      end
      new_csv += "#{cat},#{brand},#{product}\n"
    
    end
    

    那么您需要将“new_csv”保存到一个文件中,就是这样,现在您可以使用 ruby​​ 的 CSV 库来操作它。

    【讨论】:

      猜你喜欢
      • 2021-11-15
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      相关资源
      最近更新 更多