Python循环迭代,在一个lin中合并多行

2024-10-01 11:37:12 发布

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

我有一个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:

^{pr2}$

它确实把整句话和前一行连在一起。但当它碰到一个双空格或双线时,它会失败并将其注册为一个新行。例如,如果我打印:

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

如何合并列“Info”上的完整文本,使其始终与相应的DAT行匹配,而不是作为新行弹出,而不管是空字符还是新行字符?在


Tags: 文件ofcsvthetodatawithline
2条回答

在迭代时更改data是“错误的”

new_data = []
for line in data:
    if not new_data or line.startswith(condition):
        new_data.append(line)
    else:
        new_data[-1] += line
print new_data

可以将带有正则表达式的行直接拆分为data

Python

import re

f = open("myfile.csv")
text = f.read()
data = re.findall("\n(DAT\d+.*)", text)

如果不管用,请纠正我。在

更新:

我相信,这将解决新线路的问题:

^{pr2}$

相关问题 更多 >