【问题标题】:how to overwrite a html file in R如何覆盖R中的html文件
【发布时间】:2020-03-23 13:43:46
【问题描述】:

我正在尝试将 html 文件中的电子邮件地址替换为 ANTI SPAM 格式,然后再次将其导出为 nospam.html 文件。 我尝试使用 gsub() 函数来执行此操作,但它似乎不起作用。有什么问题? 谢谢!!!

datei <- scan("https://isor.univie.ac.at/about-us/People.html", sep = "\n", what= "character")
#pattern.email <- "[a-z]+[.]+[a-z]+?[@]+[a-z]+"
reg.email <- "\\<[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\>" #works

stelle.email <-gregexpr(reg.email, datei, ignore.case = TRUE) #works

unlist(stelle.email)
res.email<- regmatches(datei, stelle.email)

datei2<-gsub(reg.email, "vornameDOTnameNO-SPAMunivieDOTacDOTat", x = datei)

write(datei2, file = "nospam.html")

【问题讨论】:

  • “它似乎不起作用”,您能否更具体地指出什么不起作用。
  • 我怀疑你的reg.email。您可以调试以查看它实际匹配的内容吗?我想起了这一点:“如果有疑问,请继续添加斜线,直到它起作用。” -- Joran Elias(关于如何在 R 中转义反斜杠)
  • 您对datei2 的分配存在两个问题:(1) 您正在用datei 中的静态字符串替换静态正则表达式(它永远不会发生);或者 (2) 你的意思是gsub(res.email, ...),在这种情况下你忽略了?gsub,当它说它只使用来自pattern=的第一个警告时。

标签: r gsub overwrite


【解决方案1】:

知道regmatches(用于提取匹配的子字符串)也有伴随的regmatches&lt;-函数(用于替换匹配的子字符串)可能会提供信息。见?regmatches

所以不需要gsub,只需:

datei <- scan("https://isor.univie.ac.at/about-us/People.html", sep = "\n", what= "character")
# Read 481 items
reg.email <- "\\<[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\>" #works
stelle.email <- gregexpr(reg.email, datei, ignore.case = TRUE) #works

# for proof, first look at a substring with a "known" email:
substr(datei[268], 236, 281)

### the only new/different line of code, remove your gsub
regmatches(datei, stelle.email) <- "vornameDOTnameNO-SPAMunivieDOTacDOTat"

# now look at the same portion of that one substring, now updated
substr(datei[268], 236, 281)

write(...)

【讨论】:

    猜你喜欢
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 2020-01-16
    • 2016-08-07
    相关资源
    最近更新 更多