【问题标题】:Extracting Category IDs and Category Labels from URLs Using R使用 R 从 URL 中提取类别 ID 和类别标签
【发布时间】:2013-11-25 23:35:31
【问题描述】:

假设我有以下链接:

<a class=\"MainCategory\"href=\"/cp/3951?povid=cat1070145-env172199-moduleA080112-lLinkGNAV_Electronics_Computers\">Computers</a>
<a href=\"/browse/electronics/desktop-computers/3944_3951_132982/?_refineresult=true&catNavId=3951&povid=cat1070145-env172199-moduleA080112-lLinkGNAV_Electronics_Computers_Desktops\">Desktops</a>
<a href=\"/cp/Laptops/1089430?povid=cat1070145-env172199-moduleA080112-lLinkGNAV_Electronics_Computers_Laptops\">Laptops</a>

是否有自动提取以下 IDS 的方法:3951、132982 和 1089430 及其对应的标签:计算机、台式机和笔记本电脑?

【问题讨论】:

  • 为什么不提供一些示例 URL 的使用,然后向我们展示您希望输出的样子?包括您已经尝试过的内容。
  • 抱歉,我刚刚格式化了 HTML 标记。
  • 如果你有像下面这样的任意数据,而且ID总是在不同的地方,那就更复杂了。
  • 链接是从网站检索还是存储?
  • 我从网站上检索到它们。

标签: regex r


【解决方案1】:

如果您的网址位于如下向量中

vec <- c("<a class=\"MainCategory\"href=\"/cp/3951?povid=cat1070145-env172199-moduleA080112-lLinkGNAV_Electronics_Computers\">Computers</a>",
         "<a href=\"/browse/electronics/desktop-computers/3944_3951_132982/?_refineresult=true&catNavId=3951&povid=cat1070145-env172199-moduleA080112-lLin kGNAV_Electronics_Computers_Desktops\">Desktops</a>",
         "<a href=\"/cp/Laptops/1089430?povid=cat1070145-env172199-moduleA080112-lLinkGNAV_Electronics_Computers_Laptops\">Laptops</a>")

您可以使用正则表达式来提取信息:

data.frame(ID = sub(".*[0-9]+_[0-9]+_([0-9]+).*", "\\1", 
                    sub(".*[^0-9]([0-9]+)\\?povid.*", "\\1", vec)),
           Label = sub(".*>(.*)</a>$", "\\1", vec))

#        ID     Label
# 1    3951 Computers
# 2  132982  Desktops
# 3 1089430   Laptops

【讨论】:

  • 也许你应该提到使用正则表达式提取HTML属性不是一个好主意......
猜你喜欢
  • 1970-01-01
  • 2012-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多