【发布时间】:2016-12-05 13:42:38
【问题描述】:
是否可以在分别通过标准输入和标准输出发送输入和捕获输出时将编码设置为 utf-8,以便保留 (™)、à 等特殊字符?
这是我的代码(我使用的是 Windows,我认为输出具有这种编码:IBM866):
require 'open3'
require 'pragmatic_segmenter' # just a gem that segments paragraphs to sentences
Open3.popen3("tagger") do |stdin, stdout, stderr, wait_thread|
tokenized_group = Proc.new do |sentences|
sentences_array = PragmaticSegmenter::Segmenter.new(text: sentences).segment
sentences_array.map do |sentence|
stdin.puts "#{sentence}"
stdout.gets.gsub(/\n$/,"").encode("utf-8") #=> is it possible to get this utf-8, right now its IBM866?
end
end
puts tokenized_group.call "Some random sentence with ™. Another random sentence with à."
#output => Some/DT random/JJ sentence/NN with/IN тДв/NN ./. Another/DT random/JJ sentence/NN with/IN ├а/NN ./.
stdin.close
end
正如您所见,由于编码不同,输出中不会保留特殊字符。那么,我怎样才能找回标准输出中的那些字符呢?
【问题讨论】:
-
为什么你认为输出有 IBM866 编码?
stdout.internal_encoding和.external_encoding返回什么?sentences_array中的项目的编码是什么?返回字符串中相关字符的实际字节值是多少? -
@Jordan 当我尝试做 string.match 时,它给出了错误
incompatible encoding regexp match (UTF-8 regexp with IBM866 string) (Encoding::CompatibilityError)。internal_encoding返回零,external_encoding returnsIBM866。对于 ™(返回 тДв),它的[209, 130, 208, 148, 208, 178]对于 à(返回 ├а)它的[226, 148, 156, 208, 176]