我正在处理一个包含来自网络的数据的文件,并且在某些日志文件上遇到UTF-8 中的无效字节序列 (ArgumentError)错误。
a = File.readlines('log.csv').grep(/watch\?v=/).map do |s|
s = s.parse_csv;
{ timestamp: s[0], url: s[1], ip: s[3] }
end
puts a
我正试图让这个解决方案发挥作用。我见过人们在做
.encode!('UTF-8', 'UTF-8', :invalid => :replace)
但它似乎不适用于File.readlines
.
File.readlines('log.csv').encode!('UTF-8', 'UTF-8', :invalid => :replace).grep(/watch\?v=/)
' : 未定义的方法 `encode!' 对于 # (NoMethodError)
在文件读取期间过滤/转换无效 UTF-8 字符的最直接方法是什么?
尝试 1
试过这个,但它失败了,同样的无效字节序列错误。
IO.foreach('test.csv', 'r:bom|UTF-8').grep(/watch\?v=/).map do |s|
# extract three columns: time stamp, url, ip
s = s.parse_csv;
{ timestamp: s[0], url: s[1], ip: s[3] }
end
解决方案
这似乎对我有用。
a = File.readlines('log.csv', :encoding => 'ISO-8859-1').grep(/watch\?v=/).map do |s|
s = s.parse_csv;
{ timestamp: s[0], url: s[1], ip: s[3] }
end
puts a