【问题标题】:I have a nested hash and want to get the value of one of the key我有一个嵌套的哈希,想要获取其中一个键的值
【发布时间】:2016-02-10 20:33:46
【问题描述】:

我有一个嵌套哈希

[{:page=>1, 
:lines=>[
{:y=>774.0, :text_groups=>[{:x=>18.0, :width=>421.59599999999995, :text=>"-*- Demonstration Powered by HP Exstream 04/21/2015, Version 9.0.104 32-bit -*-"}]}, 
{:y=>762.0, :text_groups=>[{:x=>504.24, :width=>53.78399999999999, :text=>"July 16, 2014"}]}, 
{:y=>699.12, :text_groups=>[{:x=>54.0, :width=>80.01709144799977, :text=>"Capital One Auto Finance"}]}, 
{:y=>690.9599999999999, :text_groups=>[{:x=>54.0, :width=>59.619068135999825, :text=>"7933 Preston Road"}]}, 
{:y=>682.8, :text_groups=>[{:x=>54.0, :width=>53.450022959999956, :text=>"Plano, TX 75024"}]},...........

[{:page=>2, :lines=>[.....

这是 PDF 内容的哈希值。 当给定键值对:y=>"690.9599999999999"、:x=>"54.0" 和 :width=>"59.619068135999825"

时,我想获得“文本”“7933 Preston Road”的值

基本上我在这里要做的是,在作为字母的 PDF 中,我试图找出给定坐标处存在的文本。 我可以将 PDF 内容放入哈希中,但无法搜索并打印所需坐标的文本。

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 坐标是否固定且每次都相同?
  • 长浮点值可能会受到少量抖动的影响。多近才够近?
  • 现在我们假设坐标是固定的
  • 不确定浮点值。我想我们可以说+或-一两个地方。这行得通吗?

标签: ruby-on-rails ruby pdf hash hashmap


【解决方案1】:

也许更丑,而且没有公差

def find_location(pdf, y, x ,width)
  pdf.each do |page_hash|
    y_lines = page_hash[:lines].select{|line_hash| line_hash[:y] == y }
    y_lines.each do |y_line|
      y_line[:text_groups].each do |text_group|
        if text_group[:x] == x && text_group[:width] == width
          return text_group[:text]
        end
      end
    end
    return nil # Could not find text at that location.
  end
end

puts find_location(pdf, 690.9599999999999, 54.0, 59.619068135999825)

【讨论】:

  • 类 ClassXXX; def self.find_location(...); ... ;结尾;结尾; ClassXXX.find_location(...);
  • 我有多个页面,当我想要第二页或第三页的文本时,我该怎么做?
  • 此代码遍历所有页面。 page_hash 变量包含一个 :page 键。您可以添加一个页面参数并在循环中检查它。类似next unless page_hash[:page] == page
  • 对不起,代码遍历每个页面,直到找到第一个结果。使用 next 可以让你跳到你正在寻找的页面。
【解决方案2】:

有点难看,但它有效。您需要调整公差。假设 pdf 是您的哈希数据数组。

y = 690.959999999
x = 54.01
width = 59.619068135999
texts = pdf.map do |page|
  page[:lines].
    select {|e| (y - e[:y]).abs < 0.1}.
    map {|e| e[:text_groups]}.
    flatten.
    select {|e| (x - e[:x]).abs < 0.1 && (width - e[:width]).abs < 0.1}.
    map {|e| e[:text]}
end

puts texts.join

【讨论】:

  • 谢谢。它正在工作,但显示结果 4 次。7933 Preston Road7933 Preston Road7933 Preston Road7933 Preston Road
  • 它基本上是在 PDF 中的所有 4 页中给我该位置的文本我如何限制它以逐页给我。
  • 这个我就交给你了。您只需要调整它的循环方式以按页面将其分开。
猜你喜欢
  • 2021-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-16
  • 2014-10-17
  • 1970-01-01
  • 2012-09-01
相关资源
最近更新 更多