使用 Ruby 拆分 CSV 样式的字符串

发布于 2024-10-12 00:59:44 字数 249 浏览 1 评论 0原文

我有来自已加载到内存中的 CSV 文件的数据。所以我可能会有这样的事情:

csv_string = 'Value 1,Value 2,"Hey, it\'s value 3!",Value 4 has "some quotes"'

显然我不想做 csv_string.split(",")。由于以这种方式分割 CSV 样式的字符串似乎并不是一种不常见的需求,所以我想知道是否已经有解决方案。

I have data from a CSV file that's already loaded into memory. So I might have something like this:

csv_string = 'Value 1,Value 2,"Hey, it\'s value 3!",Value 4 has "some quotes"'

Obviously I won't want to do csv_string.split(","). Since it seems like splitting a CSV-style string this way might be a not-all-that-uncommon need, I was wondering if there's a solution already out there.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤独陪着我 2024-10-19 00:59:44

为了解析 CSV,Ruby 附带了 csv库:

require 'csv'

CSV.parse(csv_string)
# => [['Value 1', 'Value 2', "Hey, it's value 3!", 'Value 4 has "some quotes"']]

不幸的是,您的字符串实际上并不包含有效的 CSV,因此您将真正得到以下异常:

# CSV::MalformedCSVError: Illegal quoting on line 1.

由于您的数据实际上不符合任何通用标准,因此显然不能成为一个通用的解析器,你必须编写自己的解析器。

或者,您可以将数据更改为有效的 CSV,例如:

c = %q[Value 1,Value 2,"Hey, it's value 3!","Value 4 has ""some quotes"""]

CSV.parse(c)
# => [['Value 1', 'Value 2', "Hey, it's value 3!", 'Value 4 has "some quotes"']]

For parsing CSV, Ruby comes with the csv library:

require 'csv'

CSV.parse(csv_string)
# => [['Value 1', 'Value 2', "Hey, it's value 3!", 'Value 4 has "some quotes"']]

Unfortunately, your string doesn't actually contain valid CSV, so what you'll really get is the following exception:

# CSV::MalformedCSVError: Illegal quoting on line 1.

Since your data doesn't actually conform to any common standard, there can obviously not be a common parser and you'll have to write your own.

Alternatively, you could change your data to be valid CSV, for example like this:

c = %q[Value 1,Value 2,"Hey, it's value 3!","Value 4 has ""some quotes"""]

CSV.parse(c)
# => [['Value 1', 'Value 2', "Hey, it's value 3!", 'Value 4 has "some quotes"']]
清浅ˋ旧时光 2024-10-19 00:59:44

在 Ruby 1.9.x 上,FasterCSV 是默认的 csv 引擎,如果您使用 1.8.x,则需要包含 gem,但请看一下 foreach 和 row 解析功能:
http://fastercsv.rubyforge.org/

on Ruby 1.9.x FasterCSV is the default csv engine, if you are using 1.8.x you will need to include the gem, but take a look at the foreach and row parsing abilities:
http://fastercsv.rubyforge.org/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文