如何将一个.txt文件读入R作为向量,每个单词都在其自己的行/行中

问题描述

标题基本上是这样说的。我想将.txt文件读入R,其中所有空格和标点符号都有效地变成了换行符,将单词拆分为矢量或单列数据帧,其中行数等于文本文件中的单词数。

解决方法

我会先读取文件,然后将各行拆分为单词:

lines <- readLines("C:/Users/Johannes Gruber/Documents/Github/boellhessen/test.txt")
words <- strsplit(lines," ")[[1]]
head(words)
#> [1] "Title"     "basically" "says"      "it."       "I'd"       "like"

或者,您也可以使用tokenizers,它更快,更准确。

better_words <- tokenizers::tokenize_words(lines,lowercase = FALSE,strip_punct = FALSE)[[1]]
head(better_words)
#> [1] "Title"     "basically" "says"      "it"        "."         "I'd"

reprex package(v0.3.0)于2020-09-17创建