【问题标题】:Extract a section of a string in R [duplicate]在R中提取字符串的一部分[重复]
【发布时间】:2017-03-06 19:04:53
【问题描述】:

我需要从 Twitter 输出中提取一段字符串。我正在做的提取是使用以下代码:

some_tweets = searchTwitter('weather', n=4, lang='en')
st <- twListToDF(some_tweets)
st[,"statusSource"]

输出类似于:

[1] "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>"  
[2] "<a href=\"http://www.facebook.com/twitter\" rel=\"nofollow\">Facebook</a>"               
[3] "<a href=\"http://instagram.com\" rel=\"nofollow\">Instagram</a>"                         
[4] "<a href=\"http://www.hootsuite.com\" rel=\"nofollow\">Hootsuite</a>"  

我要提取的是最后一段:

Twitter for iPhone
Facebook
Instagram
Hootsuite

我要做的是计算每种连接类型的条目数。

关于如何提取我需要计算它们的字符串的任何想法?

【问题讨论】:

  • 使用gsub("&lt;[^&gt;]+&gt;", "", st[,"statusSource"])
  • 还有可能更接近:stackoverflow.com/q/26809847/1000343
  • 我检查了一些解决方案,但我无法弄清楚。谢谢 Wiktor,这对我有用

标签: r string


【解决方案1】:

这是使用rvest 包的一种方法。

x <- c("<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>",
       "<a href=\"http://www.facebook.com/twitter\" rel=\"nofollow\">Facebook</a>",
       "<a href=\"http://instagram.com\" rel=\"nofollow\">Instagram</a>",
       "<a href=\"http://www.hootsuite.com\" rel=\"nofollow\">Hootsuite</a>")


library(rvest)

unname(sapply(x, FUN = function(m) html_text(html_nodes(read_html(m), "a"))))
[1] "Twitter for iPhone" "Facebook"           "Instagram"          "Hootsuite" 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-19
    • 2012-04-01
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    相关资源
    最近更新 更多