Printing a CP850 encoded string with Ruby (IRB)

浪尽此生 提交于 2019-12-11 23:33:57

问题


I want to open a text file (test.txt) that contains arabic text (its encoding is CP850), then print its content to STDOUT :

# coding : CP850
STDOUT.set_encoding(Encoding::CP850); # not sure if it's necessary
open('G:/test.txt',?r){|f|
    f.read.each_char{|c| print c};
    # or puts f.read;
}
gets

but it does not print the arabic characters, the output is some symbols and random characters. Using Ruby 2.2.3


回答1:


Change the encoding of the file to utf-8.

I don't know how this is accomplished in Ruby, but Django (the newer ones using Python 3), it's:

open('filename.txt', w, 'utf-8)

If you're using Python 2 it will be slightly more difficult. If so, it's worth upgrading to 3 just because it's native unicode and makes doing anything with Arabic a lot easier.



来源:https://stackoverflow.com/questions/36447724/printing-a-cp850-encoded-string-with-ruby-irb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!