【问题标题】:How can I remove the "\n" character from csv entries?如何从 csv 条目中删除“\n”字符?
【发布时间】:2016-09-21 00:58:29
【问题描述】:

我正在使用写在名为 tags.csv 的文件中的标签来播种我的数据库。我能够播种标签,但是,当我在控制台中签入时,我看到一个字符 \n 作为标签名称的最后一个字符.例如,假设 airplane 是标签名称,当我播种时,我得到标签名称为 airplane\n 我做错了什么?

我的 db/tags.csv 是包含标签条目的 csv 文件,它看起来像这样:

airplane
sleeping
travel 

现在在我的 seeds.rb 文件中(应该是为标签播种)看起来像:

puts "loading tags..."

# LOADING TAGS
GOD_USER_ID = -1
csv_text    = File.read('db/tags.csv')
csv         = CSV.parse(csv_text, :headers => true)

puts "loading tags..."

csv.each_with_index do |row, index| 
  tag = row
  if ActsAsTaggableOn::Tag.exists?(name: tag, user_id: GOD_USER_ID, privacy: 'PUBLIC') == false then
    ActsAsTaggableOn::Tag.create(name: tag, user_id: GOD_USER_ID, privacy: 'PUBLIC') 
    if index % 10 == 0
        puts "tag: #{tag} --- index: #{index}"
    end
  else
    if index % 10 == 0
        puts "tag: #{tag}\t(already exists) --- index: #{index}"
    end
  end
end

【问题讨论】:

  • '\n' 表示返回键。在逐行读取文件时,只需基本上排除行中的最后两个字符或搜索\n 子字符串并从行中删除。
  • 首先,它看起来不像一个 CSV 文件,它看起来像一个“返回”分隔文件——你可以使用任何类型的分隔符来使用 CSV 库——如果你检查一下
  • @mertyildiran 我不知道你会如何使用 File.read 方法来做到这一点

标签: ruby-on-rails csv seeding


【解决方案1】:

使用foreach应该可以正常工作

puts "loading tags..."

# LOADING TAGS
GOD_USER_ID = -1
puts "loading tags..."

CSV.foreach("#{Rails.root}/db/tags.csv", headers: true) do |row|
  if ActsAsTaggableOn::Tag.exists?(name: tag, user_id: GOD_USER_ID, privacy: 'PUBLIC')
    puts "tag: #{tag}\t(already exists) --- index: #{index}" if index % 10 == 0
  else
    ActsAsTaggableOn::Tag.create(name: tag, user_id: GOD_USER_ID, privacy: 'PUBLIC')
    puts "tag: #{tag} --- index: #{index}" if index % 10 == 0
  end
end

【讨论】:

  • 我已经解决了。不得不使用简单的 tag = row.gsub('\n', ' ') 来删除 \n
猜你喜欢
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
  • 2019-11-22
  • 2011-05-10
  • 1970-01-01
  • 2020-03-10
  • 1970-01-01
相关资源
最近更新 更多