我正在使用Windows XP上的Ruby1.8.6将一些数据从MS access2003迁移到Rake5.0(为此编写了一个MySQL任务)。
原来Windows字符串数据被编码为windows-1252,而Rails和MySQL都采用utf-8输入,因此一些字符,比如撇号,会被破坏。它们以“a”结尾,上面有口音之类的东西。
有谁知道将windows-1252字符串转换为utf-8的工具、库、系统、方法论、仪式、咒语或咒语?
发布于 2009-06-09 07:15:14
对于Ruby 1.8.6,似乎可以使用Ruby Iconv,它是标准库的一部分:
根据这个helpful article,看起来你至少可以像这样从字符串中清除不需要的win-1252字符:
ic = Iconv.new('UTF-8//IGNORE', 'UTF-8')
valid_string = ic.iconv(untrusted_string + ' ')[0..-2]然后,可以尝试执行完全转换,如下所示:
ic = Iconv.new('UTF-8', 'WINDOWS-1252')
valid_string = ic.iconv(untrusted_string + ' ')[0..-2]发布于 2009-06-04 17:27:48
如果你用的是Ruby 1.9...
string_in_windows_1252 = database.get(...)
# => "Fåbulous"
string_in_windows_1252.encoding
# => "windows-1252"
string_in_utf_8 = string_in_windows_1252.encode('UTF-8')
# => "Fabulous"
string_in_utf_8.encoding
# => 'UTF-8'发布于 2009-06-24 17:06:15
嘿,
我也遇到了同样的问题。
这些建议帮助我开始行动起来:
始终检查正确的编码名称,以便正确地提供转换工具。如有疑问,您可以使用以下命令获取iconv或recode支持的编码列表:
$ recode -l或
$ iconv -l始终从原始文件开始,并对要使用的示例进行编码:
$ recode windows-1252..u8 < original.txt > sample_utf8.txt或
$ iconv -f windows-1252 -t utf8 original.txt -o sample_utf8.txt安装Ruby1.9,因为它在编码方面对您有很大帮助。即使您不在程序中使用它,您也可以启动irb1.9会话并选择字符串来查看输出是什么。File.open在Ruby1.9中有一个新的‘模式’参数。使用它!这篇文章帮助很大:http://blog.nuclearsquid.com/writings/ruby-1-9-encodings
File.open('original.txt', 'r:windows-1252:utf-8')
# This opens a file specifying all encoding options. r:windows-1252 means read it as windows-1252. :utf-8 means treat it as utf-8 internally.祝你玩得开心,多说脏话!
https://stackoverflow.com/questions/951891
复制相似问题