【发布时间】:2015-05-28 03:48:50
【问题描述】:
我正在从感染了各种奇怪字符的外部数据库导入内容,例如
> 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是什么’混乱?底层字节是什么? -
@muistooshort,
str.encoding # => #<Encoding UTF-8>