2013-05-09 89 views
0

我有一個由單個整數標識的矢量項列表文件中的項目列表。我也有每個項目的元數據。在這種情況下,該項目是Amazon.com上的一本書,元數據具有以下列出的各種屬性。對於我的商品清單上的每本書,我都希望獲得它的標題,組,銷售排名等等。元數據包含其他組的數據,如DVD,但我不需要這些數據,並且希望跳過它們。在元數據文件中,每個項目及其屬性以「ID:」開頭,並以空行結束。我在R中嘗試了一堆工具,但沒有取得太大的成功。希望有人能幫忙。將文本數據讀入R

下面是元數據文件的摘錄,用於2本書(ID:9和ID:10)。

Id: 9 
ASIN: 1859677800 
    title: Making Bread: The Taste of Traditional Home-Baking 
    group: Book 
    salesrank: 949166 
    similar: 0 
    categories: 1 
    |Books[283155]|Subjects[1000]|Cooking, Food & Wine[6]|Baking[4196]|Bread[4197] 
    reviews: total: 0 downloaded: 0 avg rating: 0 

Id: 10 
ASIN: 0375709363 
    title: The Edward Said Reader 
    group: Book 
    salesrank: 220379 
    similar: 5 039474067X 0679730672 0679750541 1400030668 0896086704 
    categories: 3 
    |Books[283155]|Subjects[1000]|Literature & Fiction[17]|History & Criticism[10204]|Criticism & Theory[10207]|General[10213] 
    |Books[283155]|Subjects[1000]|Nonfiction[53]|Politics[11079]|History & Theory[11086] 
    |Books[283155]|Subjects[1000]|Nonfiction[53]|Social Sciences[11232]|Anthropology[11233]|Cultural[11235] 
    reviews: total: 6 downloaded: 6 avg rating: 4 
    2000-10-8 cutomer: A2RI73IFW2GWU1 rating: 4 votes: 12 helpful: 7 
    2001-5-4 cutomer: A1GE54WF2WUZ2X rating: 5 votes: 11 helpful: 8 
    2001-8-27 cutomer: A36S399V1VC4DR rating: 4 votes: 5 helpful: 3 
    2002-1-26 cutomer: A280GY5UVUS2QH rating: 3 votes: 12 helpful: 7 
    2004-4-7 cutomer: A2YHZJIU4L4IOI rating: 4 votes: 10 helpful: 2 
    2004-4-27 cutomer: A1MB83EO48TRSC rating: 4 votes: 5 helpful: 3 

回答

0

如果使用readLines你可以得到這些數據轉變爲R,只要字符串:

z <- readLines("example-text.txt") 

然後,您可以使用此初始讀取使用scan或拆分,要在每個記錄分別讀取記錄到行中。例如:

idpos <- grep("Id",z) 
scan("example-text.txt", skip=idpos[1]-1, nlines=idpos[2]-idpos[1], what="character",sep="\n") 
scan("example-text.txt", skip=idpos[2]-1, nlines=length(z)-idpos[2], what="character",sep="\n") 

然後,您可以用各種方式解析這些字符串,將它們轉換爲另一個數據結構。

1

假設發佈的數據位於名爲myfile.txt的文本文件中,請將其縮小爲可以使用的行,然後解析該行以生成長表單數據。添加一個grp列,標識來自同一個Id的字段。可以選擇使用dcast在reshape2包從長到寬的形式重塑它:

library(reshape2) 

L <- readLines("myfile.txt") 

# add other fields to the regular expression as needed 
ok <- grep("^Id:|^ *title:|^ *group:", L, value = TRUE) 

# create data frame in long form 
long <- data.frame(lab = gsub("^ *|:.*", "", ok), value = sub("^.*?: ", "", ok)) 
long$grp <- cumsum(long$lab == "Id") 

# optionally reshape it into wide form 
wide <- dcast(grp ~ lab, data = long) 

最後一行給出:

> wide 
    grp group Id        title 
1 1 Book 9 The Taste of Traditional Home-Baking 
2 2 Book 10    The Edward Said Reader