在R中下载文本文件时出现问题

时间:2018-05-01 21:27:53

标签: r

我想从Project Gutenberg下载一个文本,我已经完成了以下代码:

setwd("D:\\sourceCode")
TEXTFILE = "pg100.txt"
if (!file.exists(TEXTFILE)) {
    download.file("http://www.gutenberg.org/cache/epub/100/pg100.txt", destfile = TEXTFILE)
}
shakespeare = readLines(TEXTFILE)

我遇到的问题是我收到了以下消息:

Warning messages:
1: In readLines(TEXTFILE) : invalid or incomplete compressed data
2: In readLines(TEXTFILE) : incomplete final line found on 'pg100.txt'

实际上我正在遵循以下教程:

https://www.r-bloggers.com/text-mining-the-complete-works-of-william-shakespeare/

然后当我想用文件获取文件的长度时:

长度(莎士比亚)

我得到的数据是:

[1] 55

但是根据我之前给出链接的教程,数据应该是:

[1] 124787

有什么不对? 感谢

3 个答案:

答案 0 :(得分:4)

下载的文件是gzip存档,而不是txt文件。

手动解压缩或执行

TEXTFILE = "pg100.txt.gz"
if (!file.exists(TEXTFILE)) {
    download.file("http://www.gutenberg.org/cache/epub/100/pg100.txt", destfile = 
TEXTFILE)
}
shakespeare = readLines(gzfile(TEXTFILE))
head(shakespeare)
#[1] "The Project Gutenberg EBook of The Complete Works of William Shakespeare, by"
#[2] "William Shakespeare"
#[3] ""
#[4] "This eBook is for the use of anyone anywhere at no cost and with"
#[5] "almost no restrictions whatsoever.  You may copy it, give it away or"
#[6] "re-use it under the terms of the Project Gutenberg License included"

length(shakespeare)
#[1] 124787

更新

在Windows中,您似乎需要设置显式二进制传输模式(因为有问题的文件不是文本文件而是二进制存档):

TEXTFILE = "pg100.txt.gz"
if (!file.exists(TEXTFILE)) {
    download.file("http://www.gutenberg.org/cache/epub/100/pg100.txt", destfile = 
TEXTFILE, mode = "wb")
}
shakespeare = readLines(gzfile(TEXTFILE))

答案 1 :(得分:2)

只需包含mode参数:

download.file("http://www.gutenberg.org/cache/epub/100/pg100.txt", destfile = TEXTFILE, mode = "wb")

答案 2 :(得分:0)

由于您尝试从http://www.gutenberg.org读取文件,因此可以使用gutenbergr包。您指向的教程非常陈旧,编写时包不存在。该软件包的优点是您不会遇到下载/ readLines问题,具体取决于您的操作系统。

library(gutenbergr)

# if you know which gutenberg id it is. (EBook-No. on gutenberg website)
# otherwise use other gutenbergr code to find authors and works. See vignette for more info

# complete works of Shakespeare is EBook-No. 100
shakespeare <- gutenberg_download(100) 

head(shakespeare)
# A tibble: 6 x 2
  gutenberg_id text                                                             
         <int> <chr>                                                            
1          100 Shakespeare                                                      
2          100 ""                                                               
3          100 *This Etext has certain copyright implications you should read!* 
4          100 ""                                                               
5          100 <<THIS ELECTRONIC VERSION OF THE COMPLETE WORKS OF WILLIAM       
6          100 SHAKESPEARE IS COPYRIGHT 1990-1993 BY WORLD LIBRARY, INC., AND IS