gpt4 book ai didi

ruby-on-rails - 如何使用 Ruby 和 Nokogiri 选择数据?

转载 作者:行者123 更新时间:2023-12-03 22:41:23 24 4
gpt4 key购买 nike

我正在使用 Nokogiri 来解析来自 XML 的数据。这是数据文件的摘录:

 <table>
<tr>
<th class="indent normal">Profit and loss account</th>
<td class="notefigure"></td>
<td id="currentProfitAndLossAccount" class="figure">
(<ix:nonFraction name="uk-gaap-pt:ProfitLossAccountReserve" contextRef="current-mud" unitRef="currencyUnit" format="ixt:numdotdecimal" decimals="0" sign="-" >12,345</ix:nonFraction><span class="endnegmark">)</span>
</td>
<td id="previousProfitAndLossAccount" class="figure">
(<ix:nonFraction name="uk-gaap-pt:ProfitLossAccountReserve" contextRef="previous-mud" unitRef="currencyUnit" format="ixt:numdotdecimal" decimals="0" sign="-" >67,890</ix:nonFraction><span class="endnegmark">)</span>
</td>
</tr>
</table>

这是我使用的代码:

require 'HTTParty'
require 'Nokogiri'
require 'JSON'
require 'Pry'
require 'csv'

# this is how we request the page we're going to scrape
page = File.open("D:/accounts_file.xml") { |f| Nokogiri::XML(f) }

#this is the empty array to store the output
companies_array = []

# this is where the data is parsed

page.css('table').css('th').map do |a|
post_name = a.text
companies_array.push(post_name)
end

page.css('table').css('td').map do |a|
post_name = a.text
companies_array.push(post_name)
end

# this pushes the data into the .csv file
CSV.open('D:/financial_data','w') do |csv|
csv << companies_array
end

目前,我得到一个表格标题行,后面是表格内容,但它没有与标题对齐,即使对齐了,也远非理想。

我最理想的是 <td id> ("currentProfitAndLossAccount") 后跟相应的值,在列表中:

"currentProfitAndLossAccount","12,345"
"previousProfitAndLossAccount","67,890"

带或不带分隔符。

实际上我正在尝试整理大约 20 个字段。然后将其导入我的数据库将是一件容易的事。我有 10 万个文件要导入,但我花了一个多星期的时间才将第一个文件转换为正确的格式以进行导入。

在 Ronan Lopes 的帮助下,我现在有了以下 Ruby:

require 'HTTParty'
require 'Nokogiri'
require 'JSON'
require 'Pry'
require 'csv'

# this is how we request the page we're going to scrape
page = File.open("D:/Accounts.xml") { |f| Nokogiri::HTML(f) }

#this is an empty array where we will store the output
companies_array = []

# this is where we select the data we want to isolate

page.css('nonFraction').map{|n| { n.parent.attributes["id"].value => n.text } }

###这是不工作的部分,我认为###

post_name = n

# the next push command appends whatever is in the brackets to the companies_array storage
companies_array.push(post_name)

# this will push the storage into a csv file
CSV.open('D:/accounts.csv','w') do |csv|
csv << companies_array
end

最佳答案

不知道这是否适用于您的所有表格,但对于那个表格,这可以提供您想要的(至少它会给您其他表格的想法):

我将其解析为 HTML 而不是 XML:

page = Nokogiri::HTML(File.open("D:/Accounts.xml").read)

并且,要获得您想要的值:

page.css('nonfraction').map{|n| { n.parent.attributes["id"].value => n.text } }

它会为您提供包含您想要的键/值的散列。

关于ruby-on-rails - 如何使用 Ruby 和 Nokogiri 选择数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48524339/

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