我正在处理一个包含来自web的数据的文件,在某些日志文件上遇到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)
但它似乎不适用于CCD_ 2。
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
Ruby是否提供了一种使用指定编码执行File.read()的方法?
我正在努力让这个解决方案发挥作用。我见过有人做
.encode!('UTF-8', 'UTF-8', :invalid => :replace)
但它似乎不适用于File.readlines.
File.readlines返回一个数组。数组没有编码方法。另一方面,字符串确实有一个编码方法。
你能给上面的备选方案举个例子吗。
require 'csv'
CSV.foreach("log.csv", encoding: "utf-8") do |row|
md = row[0].match /watch?v=/
puts row[0], row[1], row[3] if md
end
或者,
CSV.foreach("log.csv", 'rb:utf-8') do |row|
如果您需要更高的速度,请使用fastercsv宝石。
这似乎对我有用。
File.readlines('log.csv', :encoding => 'ISO-8859-1')
是的,为了读取一个文件,你必须知道它的编码。
在我的情况下,脚本默认为US-ASCII,由于存在其他冲突的风险,我无权在服务器上更改它。
我做了
File.readlines(email, :encoding => 'UTF-8').each do |line|
但这对一些日语字符不起作用,所以我在下一行添加了这个,效果很好。
line = line.encode!('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')