Ruby ruby 怎么将 unicode 转换成汉字

w353284782 · May 25, 2012 · Last by sunhaolin replied at June 24, 2014 · 9782 hits

比如\u770B\u89C1 怎么将他变成汉字输出啊 在网上查的 Iconv.conv("utf-8","utf-16",str) 这个方法貌似不行啊

完整代码是

#encoding: utf-8
english_map=[]
china_map=[]
index=0
puts "系统初始化中,请等待......"
File.open("text.txt","r:utf-8").each do |i|
  english_map[index] = i.to_s.scan(/([a-zA-Z]+)=/)
  china_map[index] =i.to_s.scan(/=([\u4E00-\u9FA5]+)/)
  index+=1
end


def run_topic(result, num, english_map, china_map)
  if result==china_map[num]
    puts "正确!"
    puts "任意键继续。"
    temp=gets
  else
    puts "不正确!"
    puts "输入1查看正确意思,输入2再次作答,输入其他换一题。"
    temp=gets
    if temp.to_i == 1
      puts "正确答案为:#{china_map[num]}"
    elsif temp.to_i == 2
      run_topic(input_result(num, english_map), num, english_map, china_map)
    end
  end
end

def  input_result(num, english_map)
  puts "请输入 #{english_map[num]} 汉语意思:"
  return result=gets
end
puts "初始化完毕。"

while true
  num = rand(english_map.length-1)
  result = input_result(num, english_map)
  run_topic(result, num, english_map, china_map)
end

text.txt内容为:
feel=感觉
fill=填充
leap=跳
lip=嘴唇
...

等等

Ruby1.9 直接就可以:

s = "\u770B\u89C1"
=> "看见" 

用 puts 输出是可以 但是如果我需要判断 比如 str="\u770B\u89C1" if str=='看见'

这样就不行了

s = "\u770B\u89C1"
 => "看见" 
1.9.3p0 :002 > s == "看见"
 => true 
1.9.3p0 :003 > s.encoding
 => #<Encoding:UTF-8> 

文件是用什么格式的?

#3 楼 @hooopo 我输入 s = "\u770B\u89C1" => "\u770B\u89C1" 。。。。

#5 楼 @w353284782 先明确文件编码,然后还要确认使用的 ruby 版本

#7 楼 @fsword 文件编码就是 utf-8 嘛!ruby 是 1.9.3p125

你敢不敢把你的完整代码贴一下?

#10 楼 @hooopo 贴了,有木有救啊

如果你的 txt 文件是保存的 utf8 编码那应该没有问题的。 你要注意一下 gets 返回的结果是带回车的,要 chomp 一下才可以比较。

#12 楼 @hooopo 。。。。知道问题了 是 scan 返回的是数组而 china_map[num] 取得还是一个数组。。。。当然就不能转换成汉字了。。。。

#1 楼 @hooopo 请问 ruby 1.9 怎么反过来呢‘看见’转为‘\u770B\u89C1’

You need to Sign in before reply, if you don't have an account, please Sign up first.