如何在不解析第一行的情况下解析CSV文件?
这个类可以工作,但我不想解析我的CSV的头。
import groovy.sql.Sql
class CSVParserService {
boolean transactional = false
def sql = Sql.newInstance("jdbc:mysql://localhost/RProject", "xxx", "xxx", "com.mysql.jdbc.Driver")
def CSVList = sql.dataSet("ModuleSet")
def CSVParser(String filepath, boolean header) {
def parse = new File(filepath)
// split and populate GeneInfo
parse.splitEachLine(',') {fields ->
CSVList.add(
Module : fields[0],
Function : fields[1],
Systematic_Name : fields[2],
Common_Name : fields[3],
)
return CSVList
}
}
}我换了我的班,所以现在我有:
import groovy.sql.Sql
class CSVParserService {
boolean transactional = false
def sql = Sql.newInstance("jdbc:mysql://localhost/RProject", "xxx", "xxx", "com.mysql.jdbc.Driver")
def CSVList = sql.dataSet("ModuleSet")
def CSVParser(String filepath, boolean header) {
def parse = new File(filepath).readLines()[1..-1]
parse.each {line ->
// split and populate GeneInfo
line.splitEachLine(',') {fields ->
CSVList.add(
Module : fields[0],
Function : fields[1],
Systematic_Name : fields[2],
Common_Name : fields[3],
)
return CSVList
}
}
}
}工作正常,直到我的CSV中的这个部分:
智人白细胞介素4受体(IL4R),转录体1,mRNA
当我的解析器得到这个部分时,他将切入3(应该在1中):
智人白细胞介素4受体(IL4R)
我怎么才能解决呢?谢谢你的帮助。
-新的评论--这是我的CSV系列的第2行:
"M6.6",NA,"ILMN_1652185",NA,NA,"IL4RA;CD124",NA,"NM_000418.2","16","16p12.1a",“智人白细胞介素4受体(IL4R)”,转录变异体1,mRNA。
正如你所看到的,我的问题是“智人白细胞介素4受体(IL4R),转录体1,mRNA”;我不想在“和”之间截取文本。我的解析器应该只将',‘从引号中分离出来(但不能在引号之间使用逗号)。例如,我有:" part1“、" part2”、"part3",我只想要剪切part1、part2、part3,如果在my part2中有逗号,我不想剪掉这些逗号。
总之,我只想忽略引号中的逗号。
发布于 2009-12-11 23:45:23
好的,我有我的修正!
在这里,代码:
import groovy.sql.Sql
class CSVParserService {
boolean transactional = false
def sql = Sql.newInstance("jdbc:mysql://localhost/RProject", "xxx", "xxx", "com.mysql.jdbc.Driver")
def CSVList = sql.dataSet("ModuleSet")
def CSVParser(String filepath, boolean header) {
def parse = new File(filepath).readLines()[1..-1]
def token = ',(?=([^\"]*\"[^\"]*\")*[^\"]*$)'
parse.each {line ->
// split and populate GeneInfo
line.splitEachLine(token) {fields ->
CSVList.add(
Module : fields[0],
Function : fields[1],
Systematic_Name : fields[2],
Common_Name : fields[3],
)
return CSVList
}
}
}
}有关更多详细信息,请参见本文:Java: splitting a comma-separated string but ignoring commas in quotes
发布于 2009-12-10 22:38:10
您可以使用以下方法将文件的每一行(第一行除外)读入List:
List<String> allLinesExceptHeader = new File(filepath).readLines()[1..-1]然后,可以使用类似于上面所示的代码来解析文件的每一行(allLinesExceptHeader的一个元素)。
allLinesExceptHeader.each {line ->
// Code to parse each line goes here
}https://stackoverflow.com/questions/1884484
复制相似问题