简体   繁体   English

分割行,并在每行中保留前几列

[英]split line and keep first few columns with each new line

I am trying to create a new line every time a comma occurs but keep the first few columns with the new line. 我试图在每次出现逗号时创建新行,但将前几列保留在新行中。 For clarity: 为了清楚起见:

A    B    C,    D,
E    F    Z
G    H    I,   J,

Should look like at the end: 最后应该看起来像:

A    B    C
A    B    D
E    F    Z
G    H    I
G    H    J

I am new to python but I am trying, so I understand split would be best for me, but I have no idea how to keep the first few columns in (there are actually 7 columns to keep) and for each appearance of comma, create a new line with the first 7 columns still there 我是python的新手,但是我正在尝试,所以我知道split对我来说是最好的,但是我不知道如何保留前几列(实际上要保留7列),并且对于逗号的每种外观,请创建前7列仍在的新行

So far I tried : 到目前为止,我尝试了:

lines = df.split(",")
for column in lines:
    print(column)

which would give me: 这会给我:

A    B    C
D
E    F    Z
G    H    I
J

which is not much I know, but it is a start :) 我知道的不多,但这只是一个开始:)

import copy
example = 'A\tB\tC,\tD,\nE\tF\tZ\nG\tH\tI,\tJ,'

lines = example.split('\n')
new_text = ''
for line in lines:
    line = line.rstrip(',').split('\t')
    new_lines = [[]]
    index = 0
    for element in line:
        if ',' in element:
            new_lines.append(copy.deepcopy(new_lines[index]))
            new_lines[index].append(element.rstrip(','))
            index += 1
        else:
            new_lines[index].append(element)

    for new_line in new_lines:
        new_text += '\t'.join(new_line)+'\n'

print(new_text)

This gives 这给

A   B   C
A   B   D
E   F   Z
G   H   I
G   H   J

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM