将多个.doc合并到一个.cs中

2024-06-09 07:39:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我认为这是一个相当不寻常的问题,因为我在任何地方都找不到答案。我有大约10万字的文档(即临床报告信-所以它们都是自由文本,带有逗号、格式等),都存储在同一个文件夹中。我希望将它们合并到一个电子表格中(理想情况下是一个.csv),这样每个.doc只占用.csv的一行。在

为了使问题复杂化,每个.doc的前6个字符包括每个文件的ID号(即“123456报告.doc“-”report“名称也可能具有可变长度和字符:即“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与包含其他数据的其他电子表格进行交叉引用。在

我不确定这是否简单(也许不是我想的),但我不知道从哪里开始。我甚至不确定最好的环境来实现这一点,所以任何提示将不胜感激! 即使这包括获得一些专门为这类任务设计的软件。在

非常感谢, 马可


Tags: csv答案textinreport文件夹名称患者
2条回答

问题解决了。这是我的脚本,在数据的子样本中似乎可以很好地工作。 非常感谢大家。另外,我还设法从标题中提取了日期(为了避免使问题进一步复杂化,我省略了原来的问题,因此增加了几行代码)。在

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
}

R中,您可以使用一个循环来处理满是文件的目录,在这个循环中,使用qdap包中的read.transcript来读取并处理这些文件。qdap还将为您做一些文本分析。那个包裹的作者经常在某处,你可能会从他那里得到一个更完整的答案。但是,阅读qdap可能是你获得一个坚实的开始所需要的全部。关于循环和处理文件的细节的问题将适用于另一个问题(尽管已经有很多这样的问题,您可以通过搜索找到您需要的东西)。但下面是一个简单的循环结构,让您了解:

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
    }

相关问题 更多 >