【问题标题】:Pattern replace in RR中的模式替换
【发布时间】:2014-06-09 15:01:58
【问题描述】:

我正在使用 R 处理 Twitter 数据集,我发现很难从推文中删除用户名。

这是我的数据集的推文列中的推文示例:

[1] "@danimottale: 2 bad our inalienable rights offend their sensitivities. U cannot reason with obtuse zealotry. // So very well said."         
[2] "@FreeMktMonkey @drleegross Want to build HSA throughout lifetime for when older thus need HDHP not to deplete it if ill before 65y/o.thanks"

我想删除/替换所有以“@”开头的单词以获得此输出:

[1] "2 bad our inalienable rights offend their sensitivities. U cannot reason with obtuse zealotry. // So very well said."         
[2] "Want to build HSA throughout lifetime for when older thus need HDHP not to deplete it if ill before 65y/o.thanks"

这个 gsub 函数仅用于删除“@”符号。

gsub("@", "", tweetdata$tweets)

我想说的是,删除文本符号后面的字符,直到遇到空格或标点符号。

我开始尝试只处理空间但无济于事:

gsub("@.*[:space:]$", "", tweetdata$tweets)

这会完全删除第二条推文

gsub("@.*[:blank:]$", "", tweetdata$tweets)

这不会改变输出。

我会很感激你的帮助。

【问题讨论】:

    标签: regex r twitter


    【解决方案1】:

    您可以使用以下内容。 \S+ 匹配任何 非空白 字符(1 或更多次),然后匹配单个 空白 字符。

    gsub('@\\S+\\s', '', noRT$text)
    

    Working Demo

    编辑: 否定匹配也可以正常工作(仅使用 空格字符

    gsub('@[^ ]+ ', '', noRT$text)
    

    【讨论】:

    • 非常感谢 - 非常有帮助,可惜我不能投票,因为我是新人。
    • @user3722736 您可以通过单击赞成票数下方左侧的复选标记来检查此解决方案是否符合您的需求。
    • 使用sub 而不是gsub,因为只有一个替换。
    • 第二个字符串有多个。
    【解决方案2】:

    这里的正则表达式方法简单直接。我添加了第二个选项,允许您使用 qdap 的 genX 函数删除任意 2 个边界之间的文本。这允许您提供左右边界。

    library(qdap)
    genX(x, "@", "\\s")
    
    ## [1] "2 bad our inalienable rights offend their sensitivities. U cannot reason with obtuse zealotry. // So very well said."
    ## [2] "Want to build HSA throughout lifetime for when older thus need HDHP not to deplete it if ill before 65y/o.thanks"    
    

    【讨论】:

    • 谢谢,很高兴看到另一个解决方案。我希望我能投票给你的答案,但我还没有声誉。
    猜你喜欢
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    • 2014-12-27
    相关资源
    最近更新 更多