将文本文件作为单字符串导入 [英] Import text file as single character string

查看:65
本文介绍了将文本文件作为单字符串导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 R 中将纯文本文件作为单字符串导入?我认为这可能会有一个非常简单的答案,但是当我今天尝试这个时,我发现我找不到一个函数来做到这一点.

How do you import a plain text file as single character string in R? I think that this will probably have a very simple answer but when I tried this today I found that I couldn't find a function to do this.

例如,假设我有一个文件 foo.txt ,里面有我想要文本挖掘的内容.

For example, suppose I have a file foo.txt with something I want to textmine.

我尝试过:

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

但这仍然返回一个向量.我得到了它的工作:

but this still returned a vector. I got it working somewhat with:

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

但这是一个相当丑陋的解决方案,而且可能也不稳定.

but that is quite an ugly solution which is probably unstable too.

推荐答案

这是来自 @JoshuaUlrich 的解决方案的变体,它使用正确的大小而不是硬编码的大小:

Here's a variant of the solution from @JoshuaUlrich that uses the correct size instead of a hard-coded size:

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

请注意,readChar 会为您指定的字节数分配空间,因此 readChar(fileName, .Machine$integer.max) 效果不佳...

Note that readChar allocates space for the number of bytes you specify, so readChar(fileName, .Machine$integer.max) does not work well...

这篇关于将文本文件作为单字符串导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆