我读取了一个 XML 文件,其中包含诸如
之类的行 <Song name="Caught Up In You" id='162' duration='276610'/>
我正在读取文件
f=File.open(file)
f.each_with_index do |line,index|
if line.match('Song name="')
@songs << line
puts line if (index % 1000) == 0
end
end
但是,当我尝试使用条目时,我发现获取带有转义字符的文本,例如:
"\t\t<Song name=\"Veinte Anos\" id='3118' duration='212009'/>\n"
如何消除初始存储或后续选择中的转义字符
@songs[rand(@songs.size)]
ruby 2.0
最佳答案
您的文本没有“转义”字符。字符串的 .inspect
版本显示了这些。观察:
> s = gets
Hello "Michael"
#=> "Hello \"Michael\"\n"
> puts s
Hello "Michael"
> p s # The same as `puts s.inspect`
"Hello \"Michael\"\n"
但是,真正的答案是将此 XML 文件作为 XML 进行处理。例如:
require 'nokogiri' # gem install nokogiri
doc = Nokogiri.XML( IO.read( 'mysonglist.xml' ) ) # Read and parse the XML file
songs = doc.css( 'Song' ) # Gives you a NodeList of song els
puts songs.map{ |s| s['name'] } # Print the name of all songs
puts songs.map{ |s| s['duration'] } # Print the durations (as strings)
mins_and_seconds = songs.map{ |s| (s['duration'].to_i/1000.0).divmod(60) }
#=> [ [ 4, 36.6 ], … ]
关于ruby - 如何从字符串中删除转义字符? UTF 的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23043805/