我有一个包含数千行代码的文本文件,这些代码行是用括号括起来的关键字所包含的类别描述
Chemicals (chem)
Electrical (elec) 我需要将这些行转换为逗号分隔值,如下所示:
Chemicals, chem
Electrical, elec我使用的是:
lines = line.gsub!('(', ',').gsub!(')', '').split(',')我想知道是否有更好的方法来做这件事。
对于后人来说,这是完整的代码(基于答案)
require 'rubygems'
require 'csv'
csvfile = CSV.open('output.csv', 'w')
File.open('c:/categories.txt') do |f|
f.readlines.each do |line|
(desc, cat) = line.split('(')
desc.strip!
cat.strip!
csvfile << [desc, cat[0,cat.length-1]]
end
end发布于 2011-06-08 22:15:49
尝试如下所示:
line.sub!(/ \((\w+)\)$/, ', \1')类别将替换为给定正则表达式的第一个匹配项(在本例中,它将始终是\1关键字)。所以它基本上会用, chem来改变(chem)。
让我们使用一个文本文件创建一个示例:
lines = []
File.open('categories.txt', 'r') do |file|
while line = file.gets
lines << line.sub(/ \((\w+)\)$/, ', \1')
end
end根据问题的更新,我可以提出如下建议:
require 'csv'
csv_file = CSV.open('output.csv', 'w')
File.open('c:/categories.txt') do |f|
f.each_line {|c| csv_file << c.scan(/^(.+) \((\w+)\)$/)}
end
csv_file.close发布于 2011-06-08 22:29:50
从Ruby 1.9开始,您可以在一个方法调用中完成此操作:
str = "Chemicals (chem)\n"
mapping = { ' (' => ', ',
')' => ''}
str.gsub(/ \(|\)/, mapping) #=> "Chemicals, chem\n"发布于 2011-06-09 01:10:37
在Ruby中,一种更干净、更有效的方法是:
description, tag = line.split(' ', 2) # split(' ', 2) will return an 2 element array of
# the all characters up to the first space and all characters after. We can then use
# multi assignment syntax to assign each array element in a different local variable
tag = tag[1, (tag.length - 1) - 1] # extract the inside characters (not first or last) of the string
new_line = description << ", " << tag # rejoin the parts into a new string这将在计算上更快(如果您有很多行),因为它使用直接的字符串操作而不是正则表达式。
https://stackoverflow.com/questions/6279614
复制相似问题