我的文件内容是
blablabla
Name : 'XYZ'
Age : '30'
Place : 'ABCD'
blablabla
我怎样才能找到“姓名”,“年龄”,“地点”和商店名称“XYZ”,年龄“30”并将“ABCD”放入哈希?
应该是什么'?'在这段代码中得到那些?
data = {}
name = /Name/
age = /Age/
place = /Place/
read_lines(file) { |l|
case l
when name
data[:name] = ?
when age
data[:age] = ?
when place
data[:place]= ?
end
}
答案 0 :(得分:0)
你可以使用这样的东西。
File.WriteAllLines(@"D:\savegrp2.log",File.ReadAllLines(@"D:\savegrp.log").Skip(1));
Console.WriteLine("file saved");
输出
data = {}
keys = {:name => "Name", :age => "Age", :place => "Place"}
File.open("test.txt", "r") do |f|
f.each_line do |line|
line.chomp!
keys.each do |hash_key, string|
if line[/#{string}/]
data[hash_key] = line.strip.split(" : ")[-1].gsub("'", "")
break
end
end
end
end
答案 1 :(得分:0)
奇怪的代码,但在这种情况下:
data[:name] = l.split(':')[1] if l.match(name)
when age
data[:age] = l.split(':')[1] if l.match(age)
when place
data[:place]= l.split(':')[1] if l.match(place)
您是否对重构感兴趣?
一种选择是:
mapping =
[
{ name: :name, pattern: /Name/ },
{ name: :age, pattern: /Age/ },
{ name: :place, pattern: /Place/ }
]
data = str.split(/\r?\n|\r/).map do |line|
mapping.map{|pair|
{ pair[:name] => line.split(' : ')[1].gsub("'", "") } if line.match(pair[:pattern])
}.compact.reduce({}, :merge)
end.reduce({}, :merge)
答案 2 :(得分:0)
假设我们首先将文件读入字符串:
str = File.read('fname')
是:
str =<<_
blablabla
Name : 'XYZ'
Age : '30'
Place : 'ABCD'
blablabla
_
#=> "blablabla\nName : 'XYZ'\nAge : '30'\nPlace : 'ABCD'\nblablabla\n"
然后使用正则表达式
r = /
^ # match beginning of line
Name\s*:\s*'(.*)'\n # match 'Name`, ':' possibly surrounded by spaces, any number
# of any character in capture group 1, end of line
Age\s*:\s*'(.*)'\n # match 'Age`, ':' possibly surrounded by spaces, any number
# of any character in capture group 2, end of line
Place\s*:\s*'(.*)'\n # match 'Place`, ':' possibly surrounded by spaces, any number
# of any character in capture group 3, end of line
/x # free-spacing regex definition mode
使用String#scan形成哈希:
[:name, :age, :place].zip(str.scan(r).first).to_h
#=> {:name=>"XYZ", :age=>"30", :place=>"ABCD"}
答案 3 :(得分:0)
我会做这样的事情:
str = <<EOT
blablabla
Name : 'XYZ'
Age : '30'
Place : 'ABCD'
blablabla
EOT
str.scan(/(Name|Age|Place)\s+:\s'([^']+)/).to_h # => {"Name"=>"XYZ", "Age"=>"30", "Place"=>"ABCD"}
如果 scan
在正则表达式中看到模式组,它将创建子数组。这些可以很容易地将返回的数组数组转换为哈希值。
如果您需要将键折叠为小写,或将其转换为符号:
str.scan(/(Name|Age|Place)\s+:\s'([^']+)/)
.map{ |k, v| [k.downcase, v] } # => [["name", "XYZ"], ["age", "30"], ["place", "ABCD"]]
.to_h # => {"name"=>"XYZ", "age"=>"30", "place"=>"ABCD"}
或者:
str.scan(/(Name|Age|Place)\s+:\s'([^']+)/)
.map{ |k, v| [k.downcase.to_sym, v] } # => [[:name, "XYZ"], [:age, "30"], [:place, "ABCD"]]
.to_h # => {:name=>"XYZ", :age=>"30", :place=>"ABCD"}
或者有些变化:
str.scan(/(Name|Age|Place)\s+:\s'([^']+)/)
.each_with_object({}){ |(k,v), h| h[k.downcase.to_sym] = v}
# => {:name=>"XYZ", :age=>"30", :place=>"ABCD"}
如果示例字符串确实是完整文件,并且不会有任何其他重新发生的键/值对,那么这将起作用。如果可能有多个,则生成的哈希将不正确,因为后续对将踩踏第一个。如果文件如你所说,那么它将正常工作。