从 csv 文件中剥离单数 /

发布于 2024-12-03 13:35:14 字数 377 浏览 3 评论 0原文

我有一个 csv 文件,其中有一些区域 / 没有任何内容,并且没有任何我想删除的内容。问题是,文件中还有其他项目,其中有一个我不想删除的 / 。

举个例子:

/abc, /, akaksdhfaiwe
/, /foo, /bar

我想:

/abc,, akaksdhfaiwe
, /foo, /bar

我该怎么做?我不能使用 gsub('^/', '') 因为它会删除 /abc /foo /bar。在我的一生中,我似乎找不到“结束”。我希望 \Z 能起作用,但没有运气。

有接受者吗?

我一直在使用 fastCSV 进行大量操作,到目前为止效果非常好。

I have a csv file which has a few areas where / proceeded by nothing and proceeded by nothing that I'd like to strip out. The catch is, I also have other items in the file which have a / that I don't want to strip out.

an example:

/abc, /, akaksdhfaiwe
/, /foo, /bar

I'd like to be:

/abc,, akaksdhfaiwe
, /foo, /bar

How do I do this? I can't use gsub('^/', '') because it would strip out the /abc /foo /bar. And for the life of me, I can't seem to find an 'ends with'. I was hoping that \Z would work, no luck.

Any takers?

I've been using fasterCSV for a lot of the manipulation which has been pretty great so far.

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

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

发布评论

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

评论(2

擦肩而过的背影 2024-12-10 13:35:14

如果你的文件不是那么大,那么你可以在清理它的同时将其放入内存中,然后再次将其写出:

clean = [ ]
CSV.open(your_csv).each { |r| csv << r.map { |e| e.sub(/^\s*\/$/, '') } }
out = CSV.open(your_csv, 'wb')
clean.each { |r| out << r }  
out.close

如果你不知何故有一个非常大的 CSV 文件,无法一次全部放入内存:

out = CSV.open('tempfile.csv', 'wb')
CSV.open(your_csv).each { |r| out << r.map { |e| e.sub(/^\s*\/$/, '') } }
out.close
File.rename('tempfile.csv', your_csv)

要么应该把这个:

/abc, /, akaksdhfaiwe
/, /foo, /bar

进入

/abc,"", akaksdhfaiwe
"", /foo, /bar

If your file isn't that big then you could slurp it into memory while cleaning it up and then write it out again:

clean = [ ]
CSV.open(your_csv).each { |r| csv << r.map { |e| e.sub(/^\s*\/$/, '') } }
out = CSV.open(your_csv, 'wb')
clean.each { |r| out << r }  
out.close

If you somehow have an incredibly massive CSV file that won't fit in memory all at once:

out = CSV.open('tempfile.csv', 'wb')
CSV.open(your_csv).each { |r| out << r.map { |e| e.sub(/^\s*\/$/, '') } }
out.close
File.rename('tempfile.csv', your_csv)

Either should turn this:

/abc, /, akaksdhfaiwe
/, /foo, /bar

into

/abc,"", akaksdhfaiwe
"", /foo, /bar
允世 2024-12-10 13:35:14

使用红宝石你可以这样做:

"/asdf /, /fdsa".gsub("/,", ",")

With ruby you can do:

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