【问题标题】:Adding items to ArrayList with separation通过分隔将项目添加到 ArrayList
【发布时间】:2015-05-25 23:02:21
【问题描述】:

我正在做一个使用 ArrayLists 进行网页抓取的项目。当我抓取信息时,它会以item [0] = pencilitem [1] = $1.50 的形式返回。我希望将这些项目放在一起,或者如果可能的话,如果价格和项目都有自己的 id 会更好,但每个项目都以某种方式链接在一起,以便我可以单独引用每个项目。此外,有时在抓取时我会得到item [2] = paperitem [3] = $5.00item [4] = wide bound college ruled,其中item [4] 表示包含在需要包含在 ArrayList 或由 ids 链接的单独 ArrayList 中的项目中的可选描述和以前一样。任何想法表示赞赏。

【问题讨论】:

  • 为什么不将HashMap与有id和description的item一起使用,value就是价格?

标签: java arraylist web-scraping data-modeling


【解决方案1】:

如果您只需要名称和价格,最好的解决方案是使用 Map,其工作方式类似于 ArrayList,但您有一对 而非单个元素,例如 。 如果您需要两个以上的值,我建议您创建自己的类,例如:

   public class Item {
       private String name;
       private double price;
       private String description;
   }

使用您需要的所有额外方法,然后像这样声明您的 ArrayList;

 ArrayList<Item> items = new ArrayList<>()

【讨论】:

  • 嗯,我遇到的主要问题是,当我使用 jsoup 抓取信息时,返回的文档如下所示:Pencil $1.50 Ruler $3.00 Paper $5.00 Wide bound college ruled,除了空格之外没有分隔项目。我需要将物品原样返回,否则我将不知道哪些价格和描述对应于哪些物品。要将它们添加到地图中,看起来我需要手动添加每个值,因为有些项目有描述而有些没有,而且页面上的项目太多了,除非我是只是错过了一些东西。
  • 例如item[0] = Pencil, item [1] = $1.50, item [2] = Ruler, item [3] = $3.00, item [4] = Paper, item [5] = $5.00, item [6] = Wide bound college ruled。我不确定如何获取此列表并确保将每个项目放入适当的类别中,而不会最终将描述放入 name 变量中,反之亦然。
  • 我想我遗漏了一些东西(现在您可能已经有了解决方案),但您可能想从名称和描述中寻找差异。例如,当名称在 item[n] 中时,您知道元素 [n+1] 肯定是价格。或者,据我所知,名称可能总是以大写字母开头。我看不到任何更简单的解决方案。
【解决方案2】:

最好为你的名字、价格和描述制作一个类Item宽度变量。

然后您可以创建一个 ArrayList 来存储您的所有项目。

【讨论】:

    【解决方案3】:

    您应该将对象建模为一个类,例如“item”,并将每个值添加为该类的一个变量。例如:

    public class item{
    
        private String name;
        private double price;
        private String description; //If there's no description it could be null
    
        // Constructor
        ...
    
        // Getters and setters
       ...
    }
    

    您需要将价格格式化为双精度。

    【讨论】:

    • 一旦我创建了item 类,我如何获取从网络抓取返回的列表Pencil $1.50 Ruler $3.00 Paper $5.00 Wide bound college ruled 并确保最终为变量description 设置wide bound college ruled?我正在抓取的页面包含数百个这样的模式,其中有一个可选的描述,因此我需要设置器能够以某种方式识别什么是“名称”变量,什么不是“名称”变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    相关资源
    最近更新 更多