Ruby 2.6.3。
[我一直试图用StringIO
编码将CSV
对象解析为bom|utf-8
实例,以便将BOM字符(不需要的)剥离,并将内容编码为UTF-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
实例中删除BOM表字符?
谢谢!
仅在读取文件时处理它们,在其他任何地方都不会,甚至它只读取它们,以便可以摆脱它们。如果要为字符串使用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