【发布时间】:2014-02-04 10:00:13
【问题描述】:
我有一个我正在尝试解析的 CSV 文件,但问题是其中一个单元格包含充满空值和换行符的数据块。我需要将每一行包含在一个数组中,并将该特定单元格中的所有内容合并到相应的行中。我最近发布了一个类似的问题,答案部分解决了我的问题,但是我在构建一个循环遍历不满足特定启动条件的每一行时遇到了问题。我的代码只合并了不满足该条件的第一行,但之后就中断了。
我有:
file ="myfile.csv"
condition = "DAT"
data = open(file).read().split("\n")
for i, line in enumerate(data):
if not line.startswith(condition):
data[i-1] = data[i-1]+line
data.pop(i)
print data
对于如下所示的 CSV:
Case | Info
-------------------
DAT1 single line
DAT2 "Berns, 17, died Friday of complications from Hutchinson-Gilford progeria syndrome, commonly known as progeria. He was diagnosed with progeria when he was 22 months old. His physician parents founded the nonprofit Progeria Research Foundation after his diagnosis.
Berns became the subject of an HBO documentary, ""Life According to Sam."" The exposure has brought greater recognition to the condition, which causes musculoskeletal degeneration, cardiovascular problems and other symptoms associated with aging.
Kraft met the young sports fan and attended the HBO premiere of the documentary in New York in October. Kraft made a $500,000 matching pledge to the foundation.
The Boston Globe reported that Berns was invited to a Patriots practice that month, and gave the players an impromptu motivational speech.
DAT3 single line
DAT4 YWYWQIDOWCOOXXOXOOOOOOOOOOO
它确实将完整的句子与上一行连接起来。但是当它遇到双空格或双行时,它会失败并将其注册为新行。例如,如果我打印:
data[0]
输出是:
DAT1 single line
如果我打印:
data[1]
输出是:
DAT2 "Berns, 17, died Friday of complications from Hutchinson-Gilford progeria syndrome, commonly known as progeria. He was diagnosed with progeria when he was 22 months old. His physician parents founded the nonprofit Progeria Research Foundation after his diagnosis.
但是如果我打印:
data[2]
输出是:
Berns became the subject of an HBO documentary, ""Life According to Sam."" The exposure has brought greater recognition to the condition, which causes musculoskeletal degeneration, cardiovascular problems and other symptoms associated with aging.
代替:
DAT3 single line
如何合并“信息”列上的全部文本,使其始终与相应的 DAT 行匹配,而不是作为新行弹出,而不管空字符还是换行符?
【问题讨论】:
-
您在迭代数据时使用
pop。你不应该改变你正在迭代的东西。将您想要的数据复制到新列表中。 -
为什么不使用 cvs 模块? docs.python.org/2/library/csv.html 它能够处理各种分隔符和转义字符 在您的情况下可能是 delimiter="\t" 。
标签: python parsing loops csv merge