gpt4 book ai didi

r - 如何从电子邮件地址中提取 "domain"

转载 作者:行者123 更新时间:2023-12-04 10:47:56 25 4
gpt4 key购买 nike

我的专栏中有以下模式

xyz@gmail.com
abc@hotmail.com

现在,我想在 @ 之后提取文本及之前 .即 gmail 和 hotmail。我可以在 . 之后提取文本使用以下代码。
sub(".*@", "", email)

如何修改上面的内容以适合我的用例?

最佳答案

你:

  • 真的需要阅读 RFC 3696 的第 3 节(TLDR:@ 可以出现在多个地方)
  • 似乎没有考虑到电子邮件可以是“someone@department.example.com”、“someone.else@yet.another.department.example.com”(即天真地假设只有一个域可以在此分析中的某个时刻回来咬你)
  • 应该注意,如果您真的要寻找电子邮件“域名”,那么您还必须考虑 really constitutes a domain name and a proper suffix .

  • 所以——除非你确定你有并且总是有简单的电子邮件地址——我可以建议:
    library(stringi)
    library(urltools)
    library(dplyr)
    library(purrr)

    emails <- c("yz@gmail.com", "abc@hotmail.com",
    "someone@department.example.com",
    "someone.else@yet.another.department.com",
    "some.brit@froodyorg.co.uk")

    stri_locate_last_fixed(emails, "@")[,"end"] %>%
    map2_df(emails, function(x, y) {
    substr(y, x+1, nchar(y)) %>%
    suffix_extract()
    })
    ## host subdomain domain suffix
    ## 1 gmail.com <NA> gmail com
    ## 2 hotmail.com <NA> hotmail com
    ## 3 deparment.example.com department example com
    ## 4 yet.another.department.com yet.another department com
    ## 5 froodyco.co.uk <NA> froodyorg co.uk
    注意子域、域和后缀的正确拆分,尤其是最后一个。
    知道了这一点,我们就可以把代码改成:
    stri_locate_last_fixed(emails, "@")[,"end"] %>%
    map2_chr(emails, function(x, y) {
    substr(y, x+1, nchar(y)) %>%
    suffix_extract() %>%
    mutate(full_domain=ifelse(is.na(subdomain), domain, sprintf("%s.%s", subdomain, domain))) %>%
    select(full_domain) %>%
    flatten_chr()
    })
    ## [1] "gmail" "hotmail"
    ## [3] "department.example" "yet.another.department"
    ## [5] "froodyorg"

    关于r - 如何从电子邮件地址中提取 "domain",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40038667/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com