Ruby 2.6.3。
我一直在尝试将一个StringIO对象解析成一个使用bom|utf-8编码的CSV实例,这样就去掉了BOM字符(不需要的),并将内容编码为bom|utf-8-8:
require 'csv'
CSV_READ_OPTIONS = { headers: true, encoding: 'bom|utf-8' }.freeze
content = StringIO.new("\xEF\xBB\xBFid\n123")
first_row = CSV.parse(content, CSV_READ_OPTIONS).first
first_row.headers.first.include?("\xEF\xBB\xBF") # This returns true显然,bom|utf-8编码不适用于StringIO对象,但我发现它确实适用于文件,例如:
require 'csv'
CSV_READ_OPTIONS = { headers: true, encoding: 'bom|utf-8' }.freeze
# File content is: "\xEF\xBB\xBFid\n12"
first_row = CSV.read('bom_content.csv', CSV_READ_OPTIONS).first
first_row.headers.first.include?("\xEF\xBB\xBF") # This returns false考虑到我需要直接使用StringIO,为什么CSV会忽略bom|utf-8编码?有没有办法从StringIO实例中删除物料清单字符?
谢谢!
发布于 2019-09-27 00:34:50
露比不喜欢炸弹。它只在读取文件时处理它们,而不是在其他任何地方,即使在其他地方,它也只是读取它们,以便可以删除它们。如果字符串需要BOM表,或者在写入文件时需要BOM表,则必须手动处理。
做这件事可能有一些好办法,尽管你自己做起来很容易
if string[0...3] == "\xef\xbb\xbf"
string = string[3..-1].force_encoding('UTF-8')
elsif string[0...2] == "\xff\xfe"
string = string[2..-1].force_encoding('UTF-16LE')
# etc发布于 2019-10-08 20:09:49
我发现在StringIO string上强制对utf8进行编码并删除物料清单以生成新的StringIO是可行的:
require 'csv'
CSV_READ_OPTIONS = { headers: true}.freeze
content = StringIO.new("\xEF\xBB\xBFid\n123")
csv_file = StringIO.new(content.string.force_encoding('utf-8').sub("\xEF\xBB\xBF", ''))
first_row = CSV.parse(csv_file, CSV_READ_OPTIONS).first
first_row.headers.first.include?("\xEF\xBB\xBF") # => false 不再需要encoding选项。这可能不是内存方面的最佳选择,但它是有效的。
发布于 2020-05-13 03:49:41
Ruby2.7在IO中添加了set_encoding_by_bom方法。此方法使用字节顺序标记并设置编码。
require 'csv'
require 'stringio'
CSV_READ_OPTIONS = { headers: true }.freeze
content = StringIO.new("\xEF\xBB\xBFid\n123")
content.set_encoding_by_bom
first_row = CSV.parse(content, CSV_READ_OPTIONS).first
first_row.headers.first.include?("\xEF\xBB\xBF")
#=> falsehttps://stackoverflow.com/questions/58102188
复制相似问题