簡體   English   中英

在Ruby中從CSV中刪除具體字符串

[英]Remove concrete string from CSV in Ruby

我有一個ruby腳本,該腳本接收XML文件並從中創建CSV。 此CSV使用分號作為定界符->,但是XML的內容包含以下標記:

 - &  
 - <  
 - >

這當然會破壞CSV文件的結構。 我需要清理。 該清潔器必須用Ruby編寫。 我嘗試下一個代碼,但此操作完全破壞了文件。

#Clean up CSV file 
#Remove: & \< >

file_names = ['terms.csv']

file_names.each do |file_name|
  text = File.read(file_name)
  new_contents = text.gsub(/&/, " and ")

  # To merely print the contents of the file, use:
  puts new_contents

  # To write changes to the file, use:
  File.open(file_name, "w") {|file| file.puts new_contents }
end

file_names.each do |file_name|
  text = File.read(file_name)
  new_contents = text.gsub(/&lt;/, " < ")

  puts new_contents

  File.open(file_name, "w") {|file| file.puts new_contents }
end

file_names.each do |file_name|
  text = File.read(file_name)
  new_contents = text.gsub(/&gt;/, " > ")

  puts new_contents

  File.open(file_name, "w") {|file| file.puts new_contents }
end

我從不使用Ruby-這是我的第一次接觸。 有更好的方法做到這一點嗎?

我解決了...我將CSV分隔符從“;”更改為 到FOR循環中的“#”以創建CSV文件。 這不是理想的解決方案,但可以。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM