从文本中删除除特定单词以外的所有内容

Remove Everything Except Specific Words From Text

我正在使用 R 处理 Twitter 数据。我有一个大型数据框,我需要从文本中删除除特定信息之外的所有内容。具体来说,我想删除除统计信息之外的所有内容。所以基本上,我想保留数字以及 "half"、"quarter"、"third" 等词。还有一种方法可以保留 "£"、"%"、"$"?

等符号

我一直在使用“gsub”来尝试这样做:

df$text <- as.numeric(gsub(".*?([0-9]+).*", "\1", df$text))

此代码删除了除数字以外的所有内容,但是有关任何单词的信息都消失了。我正在努力弄清楚如何才能在文本中保留特定的单词以及数字。

这是一个模拟数据框:

text <- c("here is some text with stuff inside that i dont need but also some that i do, here is a word half and quarter also 99 is too old for lego", "heres another one with numbers 132 1244 5950 303 2022 and one and a half", "plz help me with code i am struggling")

df <- data.frame(text)

我希望能够以数据帧输出结束:

此外,我在图片中加入了 N/A table,因为我的一些观察既没有数字也没有具体的词。这段代码的目标实际上只是能够说出这些观察包含某种形式的统计语言,而这些其他观察不包含。

非常感谢任何帮助,我会尽力回答任何问题!

我确信有更优雅的解决方案,但我相信这会实现您想要的!

df$newstrings <- unlist(lapply(regmatches(df$text, gregexpr("half|quarter|third|[[:digit:]]+", df$text)), function(x) paste(x, collapse = "")))
df$newstrings[df$newstrings == ""] <- NA


> df$newstrings
# [1] "halfquarter99"          "132124459503032022half" NA  

您可以捕获需要保留的内容,然后匹配和使用任何字符以替换为对组值的反向引用:

text <- c("here is some text with stuff inside that i dont need but also some that i do, here is a word half and quarter also 99 is too old for lego", "heres another one with numbers 132 1244 5950 303 2022 and one and a half", "plz help me with code i am struggling")
gsub("(half|quarter|third|\d+)|.", "\1", text)

参见regex demo详情:

  • (half|quarter|third|\d+) - halfquarterthird 单词,或一个或多个数字
  • | - 或
  • . - 任意单个字符。

替换模式中的 </code> 将捕获的值放回结果字符串中。</p> <p>输出:</p> <pre><code>[1] "halfquarter99" "132124459503032022half" ""