我正在从外部数据库导入内容,该数据库受到各种奇怪字符的感染,例如:
> str
=> "Nature’s Variety, Best Friends Animal Society team up"
从上下文来看,’代表右单引号。在cp1252编码中:
> str.encode('cp1252')
=> "Nature\xE2\x80\x99s Variety, Best Friends Animal Society team up"
那么我该如何将它转换为正确的UTF-8字符?这是我尝试过的方法:
> str.encode('UTF-8')
=> "Nature’s Variety, Best Friends Animal Society team up"
> str.encode('cp1252').encode('UTF-8')
=> "Nature’s Variety, Best Friends Animal Society team up"
> str.encode('UTF-8', invalid: :replace, replace: '?', undef: :replace)
=> "Nature’s Variety, Best Friends Animal Society team up"
> str.encode('cp1252').encode('UTF-8', invalid: :replace, replace: '?', undef: :replace)
=> "Nature’s Variety, Best Friends Animal Society team up"
我更希望找到一种通用的重新编码方法,这样它就能处理所有这些错误编码的字符。但如果必须这样做,我将逐个搜索并替换。但我也无法使其工作:
> str.encode('cp1252').gsub('\xE2/x80/x99', "'")
=> "Nature\xE2\x80\x99s Variety, Best Friends Animal Society team up"
> str.encode('cp1252').gsub(%r{\xE2\x80\x99}, "'")
SyntaxError: unexpected tIDENTIFIER, expecting $end
> str.encode('cp1252').gsub(Regexp.escape('\xE2\x80\x99'), "'")
=> "Nature\xE2\x80\x99s Variety, Best Friends Animal Society team up"
我想这么做,但是我甚至无法将这些字符粘贴到我的REPL中:
> str.gsub('’', "'")
当我尝试时,我收到以下错误提示:
> str.gsub('C"b,b,b
* "', ",")
=> "Nature’s Variety, Best Friends Animal Society team up"
令人沮丧。有没有关于如何正确将其编码为UTF-8的建议?
编辑:根据实际字符串字节的请求:
> str.bytes.to_a.join(' ')
=> "78 97 116 117 114 101 195 162 226 130 172 226 132 162 115 32 86 97 114 105 101 116 121 44 32 66 101 115 116 32 70 114 105 101 110 100 115 32 65 110 105 109 97 108 32 83 111 99 105 101 116 121 32 116 101 97 109 32 117 112"
’
乱码时,str.encoding
是什么?底层的字节是什么? - mu is too shortstr.encoding # => #<Encoding UTF-8>
- Mori