ruby - 如何从字符串中删除转义字符? UTF 的问题?

标签 ruby xml utf-8 escaping

我读取了一个 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/

相关文章:

perl - 将字符串转换为 is0-8859-1,以 base64 格式保存到数据库,但解码后结果为 utf8

python - 使用 unicode 字符 u201c

ruby - 如何按名称运行特定的 Ruby 1.9 Test::Unit::TestCase 子类

ruby-on-rails - 是否可以使用 ruby​​ 改进来更改测试中 Controller 操作的行为?

ruby-on-rails - 将 JSON 数据嵌入 YAML 文件

java - 在 Eclipse Web 项目中的 Java Servlet 中使用 FileOutputStreams 和 Jena 模型

php - glob() 在 Windows 上找不到带有多字节字符的文件名?

ruby - 配置 Lambda 函数(Ruby) 来访问 Amazon RDS(mysql) 并执行 CRUD 操作

Android XmlPullParser 获取标签之间的值

xml - 如何从 XML 文件引用本地 XSD?