gpt4 book ai didi

python - 清理从 csv 文件中提取的字符串

转载 作者:太空宇宙 更新时间:2023-11-03 18:45:15 24 4
gpt4 key购买 nike

我正在使用 Ruby 从 csv 文件中提取某些数据,并且我想通过删除不需要的字符来清理提取的字符串。

这是我到目前为止提取数据的方式:

CSV.foreach(data_file, :encoding => 'windows-1251:utf-8', :headers => true) do |row|

#create an array for each page
page_data = []
#For each page, get the data we are interested in and save it to the page_data
page_data.push(row['dID'])
page_data.push(row['xTerm'])

pages_to_import.push(page_data)

然后我输出包含提取数据的 csv 文件

提取的输出与 csv 数据文件中的输出完全相同:

| ID    |  Term                                   |
|-------|-----------------------------------------|
| 13241 | @@106#107#my@@106#term@@ |
| 13345 | @@63#hello@@ |
| 11436 | @@55#rock@@20#my@@10015#18#world@@ |

但是,我想要达到的预期结果是:

| ID    |  Term                                   |
|-------|-----------------------------------------|
| 13241 | my, term |
| 13345 | hello |
| 11436 | rock, my, world |

关于如何实现这一目标有什么建议吗?

我使用的库:

require 'nokogiri'
require 'cgi'
require 'csv'

最佳答案

使用正则表达式,我会这样做:

%w[
@@106#107#term1@@106#term2@@
@@63#term1@@
@@55#term1@@20#term2@@10015#18#term3@@
@@106#107#my@@106#term@@
@@63#hello@@
@@55#rock@@20#my@@10015#18#world@@
].map{ |str|
str.scan(/[^@#]+?)(?=@/)
}
# => [["term1", "term2"], ["term1"], ["term1", "term2", "term3"], ["my", "term"], ["hello"], ["rock", "my", "world"]]

我的str相当于您的 row['xTerm'] 的内容.

正则表达式/[^@#]+?(?=@)/搜索 str 中的模式不包含#@并以 @ 结尾。

从字符串中的垃圾,以及您使用 Nokogiri 和 CSV 的评论,并且因为您没有将输入数据显示为 CSV 或 HTML,我不得不怀疑您是否没有破坏传入的数据不知何故,并试图在后期处理中摆脱它。如果是这样,请告诉我们您实际上在做什么,也许我们可以帮助您获取干净的数据来开始。

关于python - 清理从 csv 文件中提取的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19686542/

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