2013-09-16 81 views
1

我有一个具有以下结构额外的逗号

123, NAME1, [email protected] 
111, NAME2, [email protected] 

一个非常大的CSV文件的问题是,一些名字有一个逗号,像

699, FIRST M. LAST, Jr., [email protected] 

是否有解决这个问题的方法?原始的csv有aprox 80k条目,因此不可能手动完成。

谢谢!

+1

如何CSV文件?如果可能,您可以尝试重新导出它们,指定应该引用字符串。 – A5C1D2H2I1M1N2O1R2T1

+0

我试图让人们像这样重新导出文件,但可能需要时间。我希望有一些R魔法来解决这个问题。 – Ignacio

+0

如果没有一些数据可以使用,我无法将其转化为答案,但我认为可能是'library(“stringr”)',而str_split_fixed()'可能会导致结果。它总是一样的字符串,还是有其他的罪魁祸首(“,Esq。”)或多于一个额外的逗号? – vaettchen

回答

1

下面是使用正则表达式的R解决方案flodel对细节的答案:产生

file <- textConnection("123, NAME1, [email protected] 
111, NAME2, [email protected] 
699, FIRST M. LAST, Jr., [email protected]") 

lines <- readLines(file) 
pattern <- "^(\\d+), (.*), \\b(.*)$" 
matches <- regexec(pattern, lines) 

bad.rows <- which(sapply(matches, length) == 1L) 
if (length(bad.rows) > 0L) stop(paste("bad row: ", lines[bad.rows])) 

data <- regmatches(lines, matches) 
as.data.frame(matrix(unlist(data), ncol = 4L, byrow = TRUE)[, -1L]) 

# V1     V2     V3 
# 1 123    NAME1 [email protected] 
# 2 111    NAME2 [email protected] 
# 3 699 FIRST M. LAST, Jr. [email protected] 
2

在2个步骤,比如,你可以这样做:

## read using `fill=TRUE` 
dat <- read.table(text=' 
123, NAME1, [email protected] 
111, NAME2, [email protected] 
699, FIRST M. LAST, Jr., [email protected]',sep=',', 
        fill=TRUE, 
        header=FALSE,stringsAsFactors=FALSE) 
## concatenate names when they contain a comma 
dat$V3 <- ifelse(nchar(dat$V4)>0,paste(dat$V3,dat$V4,sep=','),dat$V3) 
dat[,-4] 
    V1    V2      V3 
1 123   NAME1  [email protected] 
2 111   NAME2   [email protected] 
3 699 FIRST M. LAST Jr., [email protected] 
+0

您的解决方案不适用于真实数据。当我读表时,我只有4列。我认为这是因为第一个额外的逗号是像csv文件中的第74个。 :_( – Ignacio

+0

你是什么意思是“在像csv文件74”? – agstudy

+0

我的意思是74行。 – Ignacio

0

我用这个简单的Python脚本到我的数据转换

import sys 

for line in open(sys.argv[1]): 
    x = line.split(',') 
    x = [token.strip() for token in x] 
    x = [x[0], '"%s"' % (",".join(x[1:-1])), x[-1]] 
    print ";".join(x) 

要运行它

python conv.py input.txt > output.txt 

后那我可以在没有问题的情况下在R中读取它。

谢谢!

0

这是一个常见的问题,以及更好的答案之一是使用scanreadLines整个混乱载入R,然后利用gsub或其他正则表达式工具的线条分割成所需的元素。

编辑:看到这个方法