1

我很难在 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 不转义我的转义字符?

4

2 回答 2

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"))
于 2013-05-03T11:15:33.117 回答
0

你可以把它们黑回去。

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

foo.count("\\")
#=> 2
于 2013-01-02T17:59:07.080 回答