在单个.csv中合并多个.doc

时间:2013-11-02 11:11:43

标签: java python linux r csv

我认为这是一个相当不寻常的问题,因为我无处可寻。我有~100000个单词文件(即临床报告字母 - 所以它们都是自由文本,逗号,格式等),它们都存储在同一个文件夹中。我希望将它们合并到一个电子表格(理想情况下是.csv)中,以便每个.doc占用.csv的一行。

为了使问题复杂化,每个.doc的前6个字符包括每个文件的ID号(即'123456report.doc' - '报告'名称也可能具有可变长度和字符:即'123456John Smith报告。 doc'或'123457Jack Ryan Rep 01 01 2013.doc')。最初我将.doc存储在包含ID号的单个文件夹中(实际上它是一个子文件夹系统,文件夹名称的串联给出了.doc的ID号,然后我设法将其添加到文件名中) - 让我知道这是否有用,我可以更详细地解释。)

因此,.csv所需的最终结构是:

ID, Clinical report
123456, clinical text in document 123456report1.doc
123457, clinical text in document 123457report2.doc
123458, clinical text in document 123458report3.doc
...

请注意,ID可能会在数据表中重复出现(例如,如果对患者进行多次检查,则会为一位患者发布多份报告)并且必须允许我将此ID与包含其他数据的其他电子表格交叉引用。< / p>

我不确定这是否简单(可能不是我想的),但我不知道从哪里开始。我甚至不确定实现这一目标的最佳环境,因此任何提示都将不胜感激! 即使这包括获取专门为此类任务设计的某些软件。

非常感谢, 马可

2 个答案:

答案 0 :(得分:0)

R中,您可以使用循环来处理完整文件的目录,并在循环内部使用程序包read.transcript中的qdap来读取文件并对其进行处理。 qdap也会为您做一些文本分析。这个软件包的作者定期上传,你可以从他那里得到更全面的答案。但是,阅读qdap可能就是获得稳固开端所需的全部内容。关于制作循环的问题和处理文件的细节将适用于另一个问题(虽然已经有很多这样的问题,你可以通过搜索SO找到你需要的东西)。但是这里有一个简单的循环结构,可以给你一个想法:

files <- list.files(pattern = "\\.(docx|DOCX)")
files.noext <- substr(basename(files), 1, nchar(basename(files)) - 4)
out.files <- paste(files.noext, "csv", sep = "")

for (i in 1:length(files)) {
    # process the files here with qdap, accumulating the results into a new
    # structure to be determined; write out as csv
    # you might need two passes, one to unpack the docx, then one to assemble them
    # into a single structure for further analysis
    }

答案 1 :(得分:0)

问题解决了。这是我的脚本,似乎在数据的子样本中工作正常。 非常感谢大家。另外我也设法从标题中提取日期(我把原来的问题留下来,以避免使其进一步复杂化 - 因此额外的几行代码)。

files     <- list.files(pattern = "\\.(txt)")
files.ID  <- substr(basename(files), 1, 7)  #SUBSTR() takes the first 7 characters of the name of each file

#TO OBTAIN THE DATE FROM THE FILE TITLE
a <- unlist(strsplit(unlist(files), "[^0-9]+"))  #takes all the numeric sequences from each string in the vector "files" - the first one is a space (all filenames have a space as first character - the second is the ID, the third is the date as DDMMYY ("010513")
b <- a[seq(3, length(a), 3)]  #I take only the every 3rd string which is the sequence of the date.
d <- paste(substr(b,1,2),"/",substr(b,3,4),"/",substr(b,5,6), sep="") #creates the date as dd/mm/yy
files.date <- as.POSIXct(d,format="%d/%m/%Y")

x <- length(files)
j <- 1
reports<-data.frame(matrix(0,x,3))
names(reports)<-c("ID","date","text") #creates data frame with columns ID and Text
for (i in 1:x) {
  texto<-paste(readLines(files[i]),collapse="\n ")
  strip(texto,char.keep=c(".","?","!","-","+","±","~","=","&","%","$","£","@","*","(",")",":",";",">","<"))
  reports$ID[i] <- files.ID[i]
  reports$date[i] <- files.date[i]
  reports$text[i] <- texto
}
相关问题