2016-11-29 20 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")