用字符串中的一部分替换tibble中的字符串

3

我在这里搜索了很多正则表达式的答案,但找不到解决这种问题的方法。

我的数据集是一个带有维基百科链接的tibble:

library(tidytext)
library(stringr)
text.raw <- "Berthold Speer was een [[Duitsland (hoofdbetekenis)|Duits]] [[architect]]."

我正在尝试清理我的文本中的链接。

str_extract_all(text.raw, "[a-zA-Z\\s]+(?=\\])")
# [1] "Duits"     "architect"

选择我需要的单词,它们位于括号之间。
这是:
str_replace_all(text.raw, "\\[\\[.*?\\]\\]", str_extract(text.raw, "[a-zA-Z\\s]+(?=\\])"))
# [1] "Berthold Speer was een Duits Duits."

功能正常,但不完全符合我的需求。这个:

str_replace_all(text.raw, "\\[\\[.*?\\]\\]", str_extract_all(text.raw, "[a-zA-Z\\s]+(?=\\])"))
# Error: `replacement` must be a character vector

在我期望的位置,出现了一个错误:"Berthold Speer was een Duits architect"

目前我的代码大致如下:

text.clean <- data_frame(text = text.raw) %>%
  mutate(text = str_replace_all(text, "\\[\\[.*?\\]\\]", str_extract_all(text, "[a-zA-Z\\s]+(?=\\])")))

我希望有人能提供解决方案,或者指出是否存在类似问题。我想要的输出结果是"Berthold Speer was een Duits architect"


你想在结尾处拥有什么字符串? - Eric Watt
architect. I want the dots in [[ ... ]] or [[ xxx | ... ]] - raoul
text.raw %>% gsub(pattern = '\\[.+\\|', replacement = '') %>% gsub(pattern = '\\]|\\[', replacement = '') - Sean Lin
尝试使用gsub("\\[{2}(?:[^]|]*\\|)?([^]|]*)]{2}", "\\1", text),参见http://ideone.com/ffnxA2。 - Wiktor Stribiżew
1个回答

5
你可以使用单个gsub操作。
text <- "Berthold Speer was een [[Duitsland (hoofdbetekenis)|Duits]] [[architect]]."
gsub("\\[{2}(?:[^]|]*\\|)?([^]]*)]{2}", "\\1", text)

See the 在线R演示
该模式将匹配:
  • \\[{2} - 两个[符号
  • (?:[^]|]*\\|)? - 可选序列匹配
    • [^]|]* - 零个或多个字符,不包括]|
    • \\| - 竖杠符号
  • ([^]]*) - 第1组:零个或多个字符,不包括]
  • ]{2} - 两个]符号。

2
你的正则表达式技能真是太强了 +1 - Tim Biegeleisen
如果可能存在单个闭合括号,请将[^]|]*替换为[^]|]*(?:](?!])[^]|]*)*,将[^]]*替换为[^]]*(?:](?!])[^]]*)*并在gsub中添加perl=TRUE参数。 - Wiktor Stribiżew
1
只是补充一下,您仍然可以使用 stringrstr_replace_all(text, "\\[{2}(?:[^]|]*\\|)?([^]]*)]{2}", "\\1") - cderv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接