删除文件中的行 - Ruby
在 ruby 中从 CSV 文件中删除特定行中存在特定值的行的巧妙方法是什么?
这是一个文件的示例:
350 lbs., Outrigger Footprint, 61" x 53", Weight, 767 lbs., 300-2080
350 lbs., Outrigger Footprint, 61" x 53", Weight, 817 lbs., 300-2580
350 lbs., Outrigger Footprint, 61" x 53", Weight, 817 lbs., 300-2580
350 lbs., Outrigger Footprint, 69" x 61", Weight, 867 lbs., 300-3080
350 lbs., Outrigger Footprint, 69" x 61", Weight, 867 lbs., 300-3080
理想情况下,我希望仅使用以下内容创建一个新文件:
350 lbs., Outrigger Footprint, 61" x 53", Weight, 767 lbs., 300-2080
350 lbs., Outrigger Footprint, 61" x 53", Weight, 817 lbs., 300-2580
350 lbs., Outrigger Footprint, 69" x 61", Weight, 867 lbs., 300-3080
当给出以下内容时:
300-2580
300-3080
300-2080
所以我知道我可以使用 sort filename|uniq -d
来做到这一点,但我尝试学习 Ruby(有点痛苦)。
提前致谢, 中号
What is a clever way to remove rows from a CSV file in ruby where a particular value exists in a particular row?
Here's an example of a file:
350 lbs., Outrigger Footprint, 61" x 53", Weight, 767 lbs., 300-2080
350 lbs., Outrigger Footprint, 61" x 53", Weight, 817 lbs., 300-2580
350 lbs., Outrigger Footprint, 61" x 53", Weight, 817 lbs., 300-2580
350 lbs., Outrigger Footprint, 69" x 61", Weight, 867 lbs., 300-3080
350 lbs., Outrigger Footprint, 69" x 61", Weight, 867 lbs., 300-3080
Ideally, I'd want a new file created with only this:
350 lbs., Outrigger Footprint, 61" x 53", Weight, 767 lbs., 300-2080
350 lbs., Outrigger Footprint, 61" x 53", Weight, 817 lbs., 300-2580
350 lbs., Outrigger Footprint, 69" x 61", Weight, 867 lbs., 300-3080
when given this:
300-2580
300-3080
300-2080
so I know i can do this with sort filename|uniq -d
but I'm trying to learn Ruby (somewhat painfully).
Thanks in advance,
M
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用它来获取 csv 文件中数组中的唯一行
要将其写入新文件,您可以以写入模式打开文件,将其写入文件中:
要比较值,您可以使用 split 函数位于“,”上,以访问每一列,如下所示:
如果您想要更多功能,最好选择安装FasterCSV gem。
You can use this to get the unique lines in an array in a csv file
To write it to a new file, you can open a file in write mode, write this into the file:
For comparing values, you can use split function on ",", to access each column like this:
If you want more functionality, you are better off installing FasterCSV gem.
好吧,我认为这个例子不会得到您正在寻找的答案...但这会起作用...
tmp.txt =>
File.readlines('tmp.txt').uniq
将返回:因此,您还可以轻松地使用 Array fxns 进行排序。 Google ruby arrays,我相信您可以学习如何根据与所需字符串的比较来选择条目。
Well, I don't think this example will get the answer you are looking for... but this would work...
tmp.txt =>
File.readlines('tmp.txt').uniq
will return this:So, you could also easily sort with Array fxns. Google ruby arrays and I'm sure you can learn how to choose if you want an entry according to a comparison to a desired string.
您还可以创建一个不允许重复记录作为其条目的哈希。
例如,以下代码应该有所帮助:
You can also create a Hash which would NOT allow duplicate records as its entries .
For example, the following code should help: