0

我对 iconv 工具有疑问。我尝试以这种方式从 rake 文件中调用它:

Dir.glob("*.txt") do |file|
  system("iconv -f UTF-8 -t 'ASCII//TRANSLIT' #{ file } >> ascii_#{ file }")
end

但是一个文件被部分转换(部分转换的大小:10059092 字节,转换前:10081854)。比较这两个文件证明并非所有内容都写入了 ASCII。当我从 shell 显式调用此命令时,它可以完美运行。其他较小的文件转换没有问题。iconv 或 Ruby 的 system() 是否有任何限制?

4

1 回答 1

0

It is always a good idea to check the return value of system to determine whether it was successful.

Dir.glob("*.txt") do |file|
  system("iconv -f UTF-8 -t 'ASCII//TRANSLIT' #{file} >> ascii_#{file}") or
    puts "iconv failed for file #{file}: #{$?}"
end

You could also try using the Iconv standard library, and thus get rid of the system call:

require 'iconv'

source_file = 'utf8.txt'
target_file = 'ascii.txt'

File.open(target_file, 'w') do |file|
  File.open(source_file).each_line do |line|
    file.write Iconv.conv('ASCII//TRANSLIT', 'UTF-8', line)
  end
end

with appropriate error checking added.

于 2010-04-30T08:29:28.203 回答