Programming

단일 문자열로 텍스트 파일 가져 오기

procodes 2020. 5. 16. 11:18
반응형

단일 문자열로 텍스트 파일 가져 오기


R에서 일반 텍스트 파일을 단일 문자열로 어떻게 가져 옵니까? 나는 이것이 아마도 매우 간단한 대답을 가질 것이라고 생각하지만 오늘 이것을 시도했을 때 나는 이것을 할 수있는 기능을 찾을 수 없다는 것을 발견했다.

예를 들어, foo.txt텍스트 마이닝하려는 파일이 있다고 가정 합니다.

나는 그것을 시도했다 :

scan("foo.txt", what="character", sep=NULL)

그러나 이것은 여전히 ​​벡터를 반환했습니다. 나는 약간의 일을했다 :

paste(scan("foo.txt", what="character", sep=" "),collapse=" ")

그러나 그것은 아마도 불안정한 상당히 추악한 해결책입니다.


하드 코딩 된 크기 대신 올바른 크기를 사용하는 @JoshuaUlrich 솔루션의 변형은 다음과 같습니다.

fileName <- 'foo.txt'
readChar(fileName, file.info(fileName)$size)

readChar readChar(fileName, .Machine$integer.max)지정한 바이트 수의 공간을 할당하므로 제대로 작동하지 않습니다.


3 년이 지난 후에도이 질문을 계속보고있는 사람이있는 경우 Hadley Wickham의 판독기 패키지에는 편리한 read_file()기능이 있습니다.

install.packages("readr") # you only need to do this one time on your system
library(readr)
mystring <- read_file("path/to/myfile.txt")

나는 다음을 사용할 것이다. 그것은 잘 작동해야하며 적어도 나에게는 추한 것처럼 보이지 않습니다.

singleString <- paste(readLines("foo.txt"), collapse=" ")

어때요?

string <- readChar("foo.txt",nchars=1e6)

리더 패키지에는 모든 기능을 수행하는 기능이 있습니다.

install.packages("readr") # you only need to do this one time on your system
library(readr)
mystring <- read_file("path/to/myfile.txt")

패키지 stringr의 버전을 대체합니다.


Sharon의 솔루션을 더 이상 사용할 수 없어서 안타깝습니다. 내 .Rprofile 파일에 asieira의 수정 사항이있는 Josh O'Brien의 솔루션을 추가했습니다.

read.text = function(pathname)
{
    return (paste(readLines(pathname), collapse="\n"))
}

다음과 같이 사용하십시오 : txt = read.text('path/to/my/file.txt'). 나는 bumpkin (28 oct. 14) 발견을 복제 할 수 없었 writeLines(txt)으며의 내용을 보여주었습니다 file.txt. 또한 write(txt, '/tmp/out')명령 diff /tmp/out path/to/my/file.txt차이가보고되지 않았습니다.


readChar는 유연성이별로 없으므로 솔루션 (readLines 및 paste)을 결합했습니다.

또한 각 줄 사이에 공백을 추가했습니다.

con <- file("/Users/YourtextFile.txt", "r", blocking = FALSE)
singleString <- readLines(con) # empty
singleString <- paste(singleString, sep = " ", collapse = " ")
close(con)

참고 URL : https://stackoverflow.com/questions/9068397/import-text-file-as-single-character-string

반응형