通过 system() 从 Ruby 调用 iconv

发布于 2024-08-30 11:38:15 字数 337 浏览 13 评论 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() 有什么限制吗?

I have a problem with iconv tool. I try to call it from rake file in that way:

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

But one file is converted partly (size of partialy converted: 10059092 bytes, before convertion: 10081854). Comparing this two files prove that not all content was writen to ASCII. When I call this command explicit from shell it works perfectly. Other smaller files are converted without problems. Is there any limitations on iconv or Ruby's system()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

似狗非友 2024-09-06 11:38:15

检查 系统来判断是否成功。

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

您还可以尝试使用 Iconv 标准库,从而摆脱系统调用:

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

添加适当的错误检查。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文