【问题标题】:Using tidyr package in R, are we able to filter and extract links from a tibble?在 R 中使用 tidyr 包,我们是否能够从 tibble 中过滤和提取链接?
【发布时间】:2018-01-26 03:14:48
【问题描述】:

假设我的 tibble 中有这个,

Transcript                                                                                                                                                                                                                                                                                                                          
1 Hi i would like to find out more about <a href="https://mywebsite.com/internalfaq/faq/154200">http://mywebsite.com/internalfaq/faq/154200</a> please help
2 Hello my results were withheld at <a href="https://mywebsite.com/123">https://mywebsite.com/123</a> hope you can help
3 Hello my friend join me at https://mywebsite.com/456

我试过了

links = data %>%
    extract(Transcript, url.pattern)

但它并没有给我想要的东西。即使我提供了 url 模式,它也没有返回我的链接列表。它只返回我的第一个词。我做错了什么吗? 提前致谢!

这是我的网址格式:https://mywebsite.com/.*

【问题讨论】:

  • 您的示例数据中似乎没有任何链接,因此您的预期结果不清楚。
  • 对!添加了更多信息

标签: r tidyr


【解决方案1】:

必须指定extract 的into 输入。另外,请尝试在您的正则表达式中添加括号。

url.pattern <- "(https://mywebsite.com/[^> | ]*)"
data %>%
  extract(Transcript, into = 'link',regex = url.pattern)

【讨论】:

  • 哇好酷!有用。谢谢!但看起来我的正则表达式有问题。链接将始终采用这种形式mywebsite.com/12345、mywebsite.com/54321,但我当前的正则表达式给了我 mywebsite.com/12345">https://mywebsite.com/12345</a> blah blah blah。它不只是给我链接本身吗?跨度>
  • 自从我回答后,您的示例似乎发生了变化。无论如何 - 对正则表达式稍作更改以查找 ''mywebsite.com" 然后继续直到您点击 '>' 如果您有 html 格式应该可以工作。编辑的 url.pattern 应该继续直到 '>' 或空格.. . 以防另一行的 url 位于字符串中间而不是末尾的第 3 行中。
【解决方案2】:

你可以使用regmatches

 regmatches(h,gregexpr("http.*?(\\d+)",h))
[[1]]
[1] "https://mywebsite.com/internalfaq/faq/154200" "http://mywebsite.com/internalfaq/faq/154200" 

[[2]]
[1] "https://mywebsite.com/123" "https://mywebsite.com/123"

[[3]]
[1] "https://mywebsite.com/456"

这为您提供了整个网址。 h 是什么?他的Transcript[,1]。这是vector 而不是dataframe。

由于网页似乎是重复的,因此您可以使用regexpr 而不是gregexpr 来获取每个向量中的第一个:

regmatches(h,regexpr("http.*?(\\d+)",h))
[1] "https://mywebsite.com/internalfaq/faq/154200" "https://mywebsite.com/123"                   
[3] "https://mywebsite.com/456"    

您还可以将sub 函数与反向引用一起使用:

sub("(.*:)(.*\\d+)(.*)","https:\\2",h)
[1] "https://mywebsite.com/internalfaq/faq/154200" "https://mywebsite.com/123"                   
[3] "https://mywebsite.com/456"  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 2011-04-14
    • 2017-11-02
    • 1970-01-01
    • 2016-04-11
    • 2018-08-24
    • 2023-03-30
    相关资源
    最近更新 更多