在Ruby中读取带有转义字符的.text文件

时间:2013-01-02 17:27:00

标签: ruby parsing special-characters

我在使用Ruby中的转义字符读取文件时遇到了困难......

我的文本文件包含字符串“First Line \ r \ nSecond Line”,当我使用File.read时,我得到一个字符串返回,以逃脱我的转义字符:“First Line \ r \ nSecond Line”

这两个字符串不一样......

1.9.2-p318 :006 > f = File.read("file.txt")
 => "First Line\\r\\nSecond Line" 
1.9.2-p318 :007 > f.count('\\')
 => 2

1.9.2-p318 :008 > f = "First Line\r\nSecond Line"
 => "First Line\r\nSecond Line" 
1.9.2-p318 :009 > f.count('\\')
 => 0

如何让File.read无法逃脱我的转义字符?

2 个答案:

答案 0 :(得分:1)

创建一个方法来删除File.Read方法添加的所有其他转义字符,如下所示:

    # Define a method to handle unescaping the escape characters
    def unescape_escapes(s)
      s = s.gsub("\\\\", "\\") #Backslash
      s = s.gsub('\\"', '"')  #Double quotes
      s = s.gsub("\\'", "\'")  #Single quotes
      s = s.gsub("\\a", "\a")  #Bell/alert
      s = s.gsub("\\b", "\b")  #Backspace
      s = s.gsub("\\r", "\r")  #Carriage Return
      s = s.gsub("\\n", "\n")  #New Line
      s = s.gsub("\\s", "\s")  #Space
      s = s.gsub("\\t", "\t")  #Tab
      s
    end

然后在行动中看到它:

    # Create your sample file
    f = File.new("file.txt", "w")
    f.write("First Line\\r\\nSecond Line")
    f.close

    # Use the method to solve your problem
    f = File.read("file.txt")
    puts "BEFORE:", f
    puts f.count('\\')
    f = unescape_escapes(f)
    puts "AFTER:", f
    puts f.count('\\')


    # Here's a more elaborate use of it
    f = File.new("file2.txt", "w")
    f.write("He used \\\"Double Quotes\\\".")
    f.write("\\nThen a Backslash: \\\\")
    f.write('\\nFollowed by \\\'Single Quotes\\\'.')
    f.write("\\nHere's a bell/alert: \\a")
    f.write("\\nThis is a backspaces\\b.")
    f.write("\\nNow we see a\\rcarriage return.")
    f.write("\\nWe've seen many\\nnew lines already.")
    f.write("\\nHow\\sabout\\ssome\\sspaces?")
    f.write("\\nWe'll also see some more:\\n\\ttab\\n\\tcharacters")
    f.close

    # Read the file without the method
    puts "", "BEFORE:"
    puts File.read("file2.txt")

    # Read the file with the method
    puts "", "AFTER:"
    puts unescape_escapes(File.read("file2.txt"))

答案 1 :(得分:0)

你可以把他们赶回来。

foo = f.gsub("\r\n", "\\r\\n")
#=> "First Line\\r\\nSecond Line"

foo.count("\\")
#=> 2