2016-11-29 23 views
0

計算多個文件的可讀性得分我想使用koRpus軟件包計算R-3.3.2(R-Studio 3.4 for Win)的可讀性得分,並將結果保存到excel或sqllite3或txt 。 現在我只能計算一個文件的可讀性分數並將它們打印到控制檯。我試圖改進使用循環目錄的代碼,但它無法正常工作。使用R

library(koRpus) 
library(tm) 

#Loop through files 
path = "D://Reports" 
out.file<-"" 
file.names <- dir(path, pattern =".txt") 
for(i in 1:length(file.names)){ 
    file <- read.table(file.names[i],header=TRUE, sep=";", stringsAsFactors=FALSE) 
    out.file <- rbind(out.file, file) 
} 

#Only one file 
report <- tokenize(txt =file , format = "file", lang = "en") 

#SMOG-Index 
results_smog <- SMOG(report) 
summary(results_smog) 

#Flesch/Kincaid-Index 
results_fleshkin <- flesch.kincaid(report) 
summary(results_fleshkin) 

#FOG-Index 
results_fog<- FOG(report) 
summary(results_fog) 
+0

你能澄清:那你想的是閱讀這些報告是否真的分號分隔的表與標題的初始行(因爲你'read.table'通話暗示的那樣),或者他們只是純文本文檔。 –

+0

另外,你是否打算對所有連接在一起的文件執行'koRpus'調用,就好像它只是一個大文件(所以你得到一組'koRpus'結果),或者你想生成一組獨立的文件'koRpus'結果,每個文件一個? –

+0

@K。 A. Buhr我的目錄包含簡單的純文本文件。我想單獨獲取每個文件的結果,以便我可以將它們結合到一個Excel表中,並在稍後結果。 – In777

回答

1

我跑到這個相同的問題。我正在通過stackoverflow尋找解決方案,並看到您的帖子。經過一些試驗和錯誤,我想出了下面的代碼。爲我工作得很好。我拿出所有額外的信息。要找到我正在查找的分數的索引值,我首先運行它爲一個文件,並拉出了可讀性包裝的摘要。它會給你一堆不同值的表格。將列與列匹配,即可獲得要查找的特定號碼。有很多不同的選擇。

在路徑目錄中,您的文件應該是獨立的文本文件。

#Path 
path="C:\\Users\\Philipp\\SkyDrive\\Documents\\Thesiswork\\ReadStats\\" 

#list text files 
ll.files <- list.files(path = path, pattern = "txt", full.names = TRUE);length(ll.files) 

#set vectors 
SMOG.score.vec=rep(0.,length(ll.files)) 
FleshKincaid.score.vec=rep(0.,length(ll.files)) 
FOG.score.vec=rep(0.,length(ll.files)) 

#loop through each file 
for (i in 1:length(ll.files)){ 
    #tokenize 
    tagged.text <- koRpus::tokenize(ll.files[i], lang="en") 
    #hyphen the word for some of the packages that require it 
    hyph.txt.en <- koRpus::hyphen(tagged.text) 
    #Readability wrapper 
    readbl.txt <- koRpus::readability(tagged.text, hyphen=hyph.txt.en, index="all") 
    #Pull scores, convert to numeric, and update the vectors 
    SMOG.score.vec[i]=as.numeric(summary(readbl.txt)$raw[36]) #SMOG Score 
    FleshKincaid.score.vec[i]=as.numeric(summary(readbl.txt)$raw[11]) #Flesch Reading Ease Score 
    FOG.score.vec[i]=as.numeric(summary(readbl.txt)$raw[22]) #FOG score 
    if (i%%10==0) 
    cat("finished",i,"\n")} 

#if you wanted to do just one 
df=cbind(FOG.score.vec,FleshKincaid.score.vec,SMOG.score.vec) 
colnames(df)=c("FOG", "Flesch Kincaid", "SMOG") 
write.csv(df,file=paste0(path,"Combo.csv"),row.names=FALSE,col.names=TRUE) 

# if you wanted to write seperate csvs 
write.csv(SMOG.score.vec,file=paste0(path,"SMOG.csv"),row.names=FALSE,col.names = "SMOG") 
write.csv(FOG.score.vec,file=paste0(path,"FOG.csv"),row.names=FALSE,col.names = "FOG") 
write.csv(FleshKincaid.score.vec,file=paste0(path,"FK.csv"),row.names=FALSE,col.names = "Flesch Kincaid")