使用 Ruby 拆分 CSV 样式的字符串
我有来自已加载到内存中的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了解析 CSV,Ruby 附带了
csv
库:不幸的是,您的字符串实际上并不包含有效的 CSV,因此您将真正得到以下异常:
由于您的数据实际上不符合任何通用标准,因此显然不能成为一个通用的解析器,你必须编写自己的解析器。
或者,您可以将数据更改为有效的 CSV,例如:
For parsing CSV, Ruby comes with the
csv
library:Unfortunately, your string doesn't actually contain valid CSV, so what you'll really get is the following exception:
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:
在 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/