gpt4 book ai didi

ruby-on-rails - Ruby 修复多个编码文档

转载 作者:数据小太阳 更新时间:2023-10-29 07:40:00 25 4
gpt4 key购买 nike

我正在尝试检索网页,并在其上应用简单的正则表达式。一些网页包含非 UTF-8 字符,即使在 Content-Type ( example ) 中声明了 UTF-8。在这些情况下,我得到:

ArgumentError (invalid byte sequence in UTF-8)

我曾尝试使用以下方法来清理不良字符,但都没有帮助解决问题:

  1. content = Iconv.conv("UTF-8//IGNORE", "UTF-8", content)
  2. content.encode!("UTF-8", :illegal => :replace, :undef => :replace, :replace => "?")

完整代码如下:

response = Net::HTTP.get_response(url)
@encoding = detect_encoding(response) # Detects encoding using Content-Type or meta charset HTML tag
if (@encoding)
@content =response.body.force_encoding(@encoding)
@content = Iconv.conv(@encoding + '//IGNORE', @encoding, @content);
else
@content = response.body
end

@content.gsub!(/.../, "") # bang

有没有办法解决这个问题?基本上,我需要的是设置基本 URL 元标记,并将一些 Javascripts 注入(inject)到检索到的网页中。

谢谢!

最佳答案

我在导入具有不同编码的电子邮件时遇到了类似的问题,我以此结束:

def enforce_utf8(from = nil)
begin
self.is_utf8? ? self : Iconv.iconv('utf8', from, self).first
rescue
converter = Iconv.new('UTF-8//IGNORE//TRANSLIT', 'ASCII//IGNORE//TRANSLIT')
converter.iconv(self).unpack('U*').select{ |cp| cp < 127 }.pack('U*')
end
end

首先,它会尝试从 *some_format* 转换为 UTF-8,以防没有任何编码或 Iconv 由于某种原因失败,然后应用strong 转换(忽略错误, translit chars and strip non recognized chars).

让我知道它是否适合你;)

一个。

关于ruby-on-rails - Ruby 修复多个编码文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6243082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com