【问题标题】:How to correctly edit strings using regular expressions & R?如何使用正则表达式和 R 正确编辑字符串?
【发布时间】:2012-05-15 18:53:01
【问题描述】:

我将数据从制表符分隔的文本文件导入到 data.frame。现在我想调整和编辑一个名为 C1 的列的内容。为此目的向我推荐了正则表达式。一开始我用的是:

for (rn in 1:length(C1))
C1s <- strsplit(as.character(C1[rn]), "; ", fixed = TRUE)[[1]]

将这些示例中的各个条目分开:

  • [张俊玲] 中国农业大学资源与环境科学学院, 北京 100094, 人民共和国; [Zhang, Junling] Univ Hohenheim, Inst Plant Nutr, D-7000 Stuttgart, Germany; [George, Eckhard] Humboldt Univ, Inst Crop Sci, Dept Plant Nutr, D-14979 Grossbeeren, Germany; [George, Eckhard] Leibniz Inst 蔬菜和观赏作物 Theodor, D-14979 Grossbeeren, Germany
  • UNIV DORTMUND,INST PHYS,D-44221 DORTMUND,德国;洪堡大学,INST PHYS,D-15738 ZEUTHEN,德国
  • UNIV KEELE,DEPT CHEM,KEELE ST5 5BG,STAFFS,英格兰; MT SINAI HOSP,MT SINAI SCH MED,DR A A FISHBERG CTR NEUROBIOL,NEW YORK,NY 10029;柏林洪堡大学,慈善医院,病理学和临床生化部,柏林,德国
  • NIFAD,MOLEC MICROBIOL LAB,BETHESDA,MD

然后我想

  • 将所有内容设置为大写
  • 将字符串“Humboldt...Germany”替换为“HUMBOLDT”,将字符串“England”、“Scotland”、“Wales”和“North Ireland”替换为“UNITED KINGDOM”
  • 将美国各州缩写和邮政编码的组合替换为“USA”
  • 将美国各州的缩写替换为“USA”

此外,我想删除除分号(包括它们后面的空格)、它们前面的单词以及上面示例中的最后一个单词之外的所有内容。
我用过

gsub('[.*\\] ', ''(toupper(C1s))  

gsub(',\\s*', ','(toupper(C1s))  

,例如,但无法使其正常工作。
我想得到以下输出:

  • 中国人民;德国;洪堡;德国
  • 德国;洪堡
  • 联合王国;美国;洪堡
  • 美国

所以我的问题是:我怎样才能达到我想要的结果?
非常感谢您的考虑!

更新和其他问题

感谢 mrdwab 的有用回复和 cmets,我取得了很大进展。

不幸的是,直到现在我才意识到也有这样的地址,其中方括号中的作者不止一位。不幸的是,mrdwab 提出的算法不适用于这些。

> test = c("[Bocquet, F. C.; Giovanelli, L.; Abel, M.; Porte, L.; Themlin, J. -M.] Aix Marseille Univ, Inst Mat Microelect & Nanosci Prov IM2NP, F-13397 Marseille 20, France; [Bocquet, F. C.; Giovanelli, L.; Abel, M.; Porte, L.; Themlin, J. -M.] CNRS, Inst Mat Microelect & Nanosci Prov IM2NP, UMR 6242, Marseille, France; [Amsalem, P.; Koch, N.] Humboldt Univ, Inst Phys, D-12489 Berlin, Germany; [Petaccia, L.; Topwal, D.; Gorovikov, S.; Goldoni, A.] Sincrotrone Trieste, I-34149 Trieste, Italy")

这是我得到的结果:

> test
[1] "[BOCQUET,  F. C." "GIOVANELLI,  L."  "ABEL,  M."        "PORTE,  L."      
[5] "FRANCE"           "[BOCQUET,  F. C." "GIOVANELLI,  L."  "ABEL,  M."       
[9] "PORTE,  L."       "FRANCE"           "[AMSALEM,  P."    "HUMBOLDT"        
[13] "[PETACCIA,  L."   "TOPWAL,  D."      "GOROVIKOV,  S."   "ITALY" 

这是我想要得到的结果:

[1] "FRANCE"; "FRANCE"; "HUMBOLDT"; "ITALY"

我尝试使用它来单独删除每个方括号及其内容:

C1s = gsub("(.*)[(.*)]", "\\2", C1s)

但是第一个左括号和最后一个右括号之间的所有内容都被删除了...... 如果我先用逗号替换方括号内的所有分号,也许它会起作用?我试过了

C1s = gsub("[(.*);(.*)]", "[(.*),(.*)]", C1s)

实现了这一点,但没有奏效。
非常感谢您在这方面的帮助!

除此之外,我还被困在另一个障碍上,我似乎无法自己解决,不幸的是......
这是我当前的输出:

> C1s
[1] "PEOPLES R CHINA" "GERMANY"         "HUMBOLDT"         "GERMANY"
[5] "GERMANY"         "HUMBOLDT"        "UNITED KINGDOM"   "USA"
[9] "HUMBOLDT"        "USA"
> dims
[1] 4 2 3 1
> is.list(C1)
[1] FALSE
> is.vector(C1)
[1] TRUE

但是我如何准确地使用 dims 中的信息来创建所需的输出?:

[1] "PEOPLES R CHINA"; "GERMANY"; "HUMBOLDT"; "GERMANY"
[2] "GERMANY"; "HUMBOLDT"
[3] "UNITED KINGDOM"; "USA"; "HUMBOLDT"
[4] "USA"

非常感谢您的支持!

【问题讨论】:

    标签: regex r list vector dataframe


    【解决方案1】:

    假设您的数据如下所示:

    test = c("[Zhang, Junling] China Agr Univ, Coll Resources & Environm Sci, Beijing 100094, Peoples R China", 
             " [Zhang, Junling] Univ Hohenheim, Inst Plant Nutr, D-7000 Stuttgart, Germany", 
             " [George, Eckhard] Humboldt Univ, Inst Crop Sci, Dept Plant Nutr, D-14979 Grossbeeren, Germany", 
             " [George, Eckhard] Leibniz Inst Vegetable & Ornamental Crops Theodor, D-14979 Grossbeeren, Germany"
    )
    

    首先,让我们全部大写:

    test = toupper(test)
    

    那我们把HUMBODT...GERMANY改成HUMBOLDT

    test = gsub("(.*)(HUMBOLDT)(.*)", "\\2", test)
    

    那么,我们只提取字符串的最后一部分。

    test = gsub("(.*), +([A-Z ]+$)", "\\2", test)
    > test
    [1] "PEOPLES R CHINA" "GERMANY"         "HUMBOLDT"        "GERMANY"    
    

    如果我能从你那里得到一个更完整的例子,我也许可以帮助你完成其他部分。

    更新

    这是一个最有效的解决方案,应该可以帮助您弄清楚该怎么做。

    使用“扫描”从您的帖子中复制您的数据,我们可以获得如下所示的数据:

    test = c("[Zhang, Junling] China Agr Univ, Coll Resources & Environm Sci, Beijing 100094, Peoples R China; [Zhang, Junling] Univ Hohenheim, Inst Plant Nutr, D-7000 Stuttgart, Germany; [George, Eckhard] Humboldt Univ, Inst Crop Sci, Dept Plant Nutr, D-14979 Grossbeeren, Germany; [George, Eckhard] Leibniz Inst Vegetable & Ornamental Crops Theodor, D-14979 Grossbeeren, Germany", 
             "UNIV DORTMUND,INST PHYS,D-44221 DORTMUND,GERMANY; HUMBOLDT UNIV,INST PHYS,D-15738 ZEUTHEN,GERMANY", 
             "UNIV KEELE,DEPT CHEM,KEELE ST5 5BG,STAFFS,ENGLAND; MT SINAI HOSP,MT SINAI SCH MED,DR A A FISHBERG CTR NEUROBIOL,NEW YORK,NY 10029; HUMBOLDT UNIV BERLIN,CHARITE HOSP,DEPT PATHOL & CLIN BIOCHEM,BERLIN,GERMANY", 
             "NIFAD,MOLEC MICROBIOL LAB,BETHESDA,MD")
    

    您需要逐步进行才能进行所需的转换。以下是我的做法。

    test.orig = test # A backup, just in case
    test = toupper(test) # To uppercase
    test = strsplit(test, ";") # Split everything up into a list
    dims = sapply(test, length) # We might need this later
    test = unlist(test) # Now, a single vector
    test = gsub(",", " , ", test) # Pad those commas with some space
    # Replace any 'HUMBOLDT'...'GERMANY' stuff with 'HUMBOLDT'
    test = gsub("(.*)(HUMBOLDT)(.*)(GERMANY$)", "\\2", test)
    # Replace a bunch of stuff with 'UNITED KINGDOM'
    test = gsub("ENGLAND|SCOTLAND|WALES|NORTH IRELAND", "UNITED KINGDOM", test)
    # Search for a pair of letters followed by a space followed by five digits
    # and replace it with USA
    test = gsub(" [A-Z]{2} [0-9]{5}", " USA", test)
    # Find the item following the last comma
    test = gsub("(.*), ([A-Z ]+)$", "\\2", test)
    # Remove any whitespace
    test = gsub("^ | $", "", test)
    > test
    [1] "PEOPLES R CHINA" "GERMANY"         "HUMBOLDT"        "GERMANY"        
    [5] "GERMANY"         "HUMBOLDT"        "UNITED KINGDOM"  "USA"            
    [9] "HUMBOLDT"        "MD"                  
    # Unlist it if you need to
    > split(test, rep(dims, dims))
    $`1`
    [1] "MD"
    
    $`2`
    [1] "GERMANY"  "HUMBOLDT"
    
    $`3`
    [1] "UNITED KINGDOM" "USA"            "HUMBOLDT"      
    
    $`4`
    [1] "PEOPLES R CHINA" "GERMANY"         "HUMBOLDT"        "GERMANY"   
    

    但是,我会让你弄清楚如何用 USA 替换州缩写,以及如何将其放回相同的行顺序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-03
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多