【问题标题】:Using split with Nokogiri?与 Nokogiri 一起使用拆分?
【发布时间】:2023-03-15 16:53:01
【问题描述】:

我正在使用网站的 API 来检索以下信息:

5097,2593,1289766548 1541,99,65990390 934,99,73230517 3055,99,62377700
1410,99,81193882 1232,99,50959566 340,99,31225295 2303,99,46585590
91,99,200000000 2258,99,32250727 692,99,40608716 4397,99,23545788
2371,99,30486082 408,99,33064494 136,99,54937860 2410,99,23192056
858,99,30378477 1088,99,21174680 174,99,76296917 477,99,50883493
2577,99,24367856 603,99,34401457 1556,99,24433483 1115,99,22150489
1365,99,23373048 4889,120,121954995 10957,97,10702990 -1,-1 -1,-1
9460,3985121 -1,-1 -1,-1 25908,1608 17180,1538 19932,1519 33486,1651
-1,-1 2589,401 14280,1262 -1,-1 -1,-1 -1,-1 34212,360000 -1,-1 -1,-1 -1,-1

请注意,数字以 3 为一组,以逗号分隔,然后是空格,然后是下一组。

xxxx,xxxx,xxxxxxxxxx yyyy,yy,yyyyyyyy zzzz,zz,zzzzzzzz

这是我的控制器:

class PagesController < ApplicationController
  def home
    require 'open-uri'

    @username = "brink"
    @url = "http://hiscore.runescape.com/index_lite.ws?player=#{@username}"
    @doc = Nokogiri::HTML(open(@url))
  end

  def help
  end
end

这是我在视图中显示信息的方式:

<h1>Welcome to xpTrack</h1>

<p>
  <%= @username.capitalize %>
</p>

<%= @doc.text %>

有没有办法让我创建一个在每组数字之间的每个空格处拆分的数组?我试过了:

@stats = @doc.split('\n'),但返回:

undefined method `split' (some Nokogiri error)

【问题讨论】:

    标签: ruby-on-rails ruby arrays split


    【解决方案1】:

    你可以试试:

    # split on spaces
    @stats = @doc.text.split(' ')
    # => ["xxxx,xxxx,xxxxxxxxxx","yyyy,yy,yyyyyyyy","zzzz,zz,zzzzzzzz"]
    
    # split on spaces and then on commas
    @stats = @doc.text.split(' ').map { |a| a.split(",") }
    # => [["xxxx","xxxx","xxxxxxxxxx"],["yyyy","yy","yyyyyyyy"],["zzzz","zz","zzzzzzzz"]]
    

    【讨论】:

    • 这样就完成了。我会在几分钟内接受你的回答。
    • 使用第二个选项,如何引用数组中的元素?既然我已经用空格 逗号分隔了所有内容,那么如何将第一个数字放入第一个数组中?
    • @DylanRichards: @stats[0][0] 会给你第一个子数组的第一个元素。
    【解决方案2】:

    除非您使用 XML 或 HTML,否则不要使用 Nokogiri。只需使用open().read 获取一个字符串,然后将其拆分。

    另外,我怀疑.scan(/(\d+),(\d+),(\d+)/) 或其一些变体会比拆分更好。

    【讨论】:

      猜你喜欢
      • 2023-02-15
      • 2018-10-16
      • 2014-12-08
      • 2012-02-08
      • 1970-01-01
      • 1970-01-01
      • 2022-06-29
      • 1970-01-01
      • 2012-01-24
      相关资源
      最近更新 更多