【问题标题】:Cleaning Data / Truncate short URL out of data [duplicate]清理数据/从数据中截断短 URL [重复]
【发布时间】:2019-08-25 07:13:48
【问题描述】:

我目前正在清理来自 eCom 的一些 URL 数据,因为我想更好地了解引荐来源网址流量的来源。

我在 R 中尝试过 sub() 函数,但在正确应用 RegEx 时遇到了困难。

sub("*.com", "", q2$Session.First.Referrer)

我想简单地清理一个看起来像的 URL “http\://www\.gazelle\.com/main/home\.jhtml” 基本 URL 所以“www.gazelle.com”。

【问题讨论】:

  • 查看regex有关提取部分 URL 的问题。您可以将另一种语言中使用的正则表达式改编为 R
  • 在其他一些 SO 帖子中解决了很多复杂问题需要考虑:您检查 httphttps 吗?是否所有 URL 都包含 http://,还是仅以 www. 开头?是否有任何子域,例如http://stats.stackexchange.com/,这样就不会有wwwww2. 呢? .edu? .co.uk? .io?这实际上是一项比最初看起来更大的任务。

标签: r regex url text truncate


【解决方案1】:

我使用了stringr 包中的str_extract(tidyverse 的一部分):

library(tidyverse)
library(stringr)

my_data <- tibble(addresses = c("https://www.fivethirtyeight.com/features/is-there-still-room-in-the-democratic-primary-for-biden/",
                                "https://www.docs.aws.amazon.com/sagemaker/latest/dg/sms.html",
                                "https://www.stackoverflow.com/questions/55500553/cleaning-data-truncate-short-url-out-of-data"))

str_extract(my_data$addresses, "www.+com")

返回:

[1] "www.fivethirtyeight.com" "www.docs.aws.amazon.com"
[3] "www.stackoverflow.com"  

【讨论】:

    【解决方案2】:

    假设您的所有 URL 格式相同,您可以使用gsub 删除出现在“www”之前和“.com”之后的文本,参考如下:

    # Example string
    my.string = "http://www.gazelle.com/main/home.jhtml"
    > my.string
    [1] "http://www.gazelle.com/main/home.jhtml"
    
    # remove everything after .com
    output.string = gsub(".com.*",".com", my.string)
    
    # remove everything before www.
    output.string = gsub(".*www.", "www.", output.string)
    
    > output.string
    [1] "www.gazelle.com"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-04
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 2013-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多