【问题标题】:Extract words from text and create a vector from them从文本中提取单词并从中创建向量
【发布时间】:2019-11-26 13:17:37
【问题描述】:

假设,我有一个包含这样文本的 txt 文件:

Type: fruits
Title: retail
Date: 2015-11-10
Country: UK
Products:
  apple,
  passion fruit,
  mango
Documents: NDA
Export: 2.10

我用readLines 函数读取了这个文件。 然后,我想得到一个看起来像这样的向量:

x <- c(fruits, apple, passion fruit, mango)

所以,我想提取“Type:”之后的单词以及“Products:”和“Documents:”之间的所有单词。 我怎样才能做到这一点?谢谢!

【问题讨论】:

    标签: r regex gsub text-processing stringr


    【解决方案1】:

    如果它没有变化,它看起来接近yaml 格式,例如使用同名包

    library(yaml)
    info <- yaml::read_yaml("your file.txt")
    # strsplit - split either side of the commas
    # unlist - convert to vector
    # trimws - remove trailing and leading white space
    out <- trimws(unlist(strsplit(info$Products, ",")))
    

    您将在info 中获得所需名称的其他条目作为列表元素,例如info$Type

    【讨论】:

      【解决方案2】:

      也许有一个更优雅的解决方案,如果你可以尝试这个,如果你有这样的向量:

      vec <- readLines("path\\file.txt")
      

      文件中有你发布的文字,你可以试试这个:

      # replace biggest spaces
      gsub("   "," ",
           # replace the first space
           sub(" ",", ",
             # pattern to extract words
             gsub(".*Type:\\s*|Title.*Products:\\s*| Documents.*", "",
                 # collapse in one vector
                 paste0(vec, collapse = " "))))
      [1] "fruits, apple, passion fruit, mango"
      

      如果你dput(vec) 使代码可重现:

      c("Type: fruits", "Title: retail", "Date: 2015-11-10", "Country: UK", 
      "Products:", "  apple,", "  passion fruit,", "  mango", "Documents: NDA", 
      "Export: 2.10")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-01-21
        • 1970-01-01
        • 1970-01-01
        • 2014-12-30
        • 2014-06-10
        相关资源
        最近更新 更多