gpt4 book ai didi

ruby - `scan' : invalid byte sequence in UTF-8 (ArgumentError)

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

我正在尝试读取 ruby​​ 中的 .txt 文件并逐行拆分文本。

这是我的代码:

def file_read(filename)
File.open(filename, 'r').read
end

puts f = file_read('alice_in_wonderland.txt')

完美地工作。但是当我像这样添加方法 line_cutter 时:

def file_read(filename)
File.open(filename, 'r').read
end

def line_cutter(file)
file.scan(/\w/)
end

puts f = line_cutter(file_read('alice_in_wonderland.txt'))

我得到一个错误:

`scan': invalid byte sequence in UTF-8 (ArgumentError)

我找到了 this在线访问不受信任的网站,并尝试将其用于我自己的代码,但它不起作用。我怎样才能消除这个错误?

文件链接:File

最佳答案

链接的文本文件包含以下行:

Character set encoding: ISO-8859-1

如果不需要或不可能转换它,那么您必须告诉 Ruby 这个文件是 ISO-8859-1编码。否则 default external encoding使用( UTF-8 在你的情况下)。一种可能的方法是:

s = File.read('alice_in_wonderland.txt', encoding: 'ISO-8859-1')
s.encoding # => #<Encoding:ISO-8859-1>

如果您更喜欢 UTF-8 编码的字符串(请参阅 utf8everywhere.org),甚至可以这样:

s = File.read('alice_in_wonderland.txt', encoding: 'ISO-8859-1:UTF-8')
s.encoding # => #<Encoding:UTF-8>

关于ruby - `scan' : invalid byte sequence in UTF-8 (ArgumentError),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36087395/

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