Python脚本,用于在某些标准的基础上进行转置

2024-03-29 14:55:13 发布

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

我有一个包含以下格式数据的文件:

abc 123 456
cde 45 32
efg 322 654
abc 445 856
cde 65 21
efg 147 384
美国广播公司815 078 efg 843 286
等等。如何使用Python将其转换为以下格式:

abc 123 456 cde 45 32 efg 322 654
abc 445 856 cde 65 21 efg 147 348
abc 815 078 efg 843 286
另外,如果abc后面缺少cde,则应该插入空格,因为它是一个固定宽度的文件。 打开abc。作为文件: 对于文件中的行。readlines() 而行[:3]=='abc' 行。替换('\n','')

我是python新手,非常感谢您的帮助


Tags: 文件数据宽度格式空格abc新手cde
1条回答
网友
1楼 · 发布于 2024-03-29 14:55:13

@Ritesh1111,即使你是新人,也应该开始尝试一些东西。 尝试使用以下代码,只需很少的假设,它可能不是100%准确,但您可以从这里开始:

with open('abc.txt') as rd:
    data = rd.readlines()

full_detail={}
seq=['abc', 'cde', 'efg']  # Assuming the order of the sequences, also 1st must be present.   
for row in seq:
    full_detail[row] = []
last_processed = None

def get_next_seq_pos(last_seq_postition, seq):
    return last_seq_postition+1 if last_seq_postition < len(seq) - 1 else 0

for line in data:
    cline = line.strip().split(" ")
    if last_processed is None:
        data_seq_postition = seq.index(cline[0].strip())
        temp_data = " ".join([str(i) for i in cline[1:]])
        full_detail[seq[data_seq_postition]].append(temp_data)
        last_processed = seq[data_seq_postition]
    else:
        last_seq_postition = seq.index(last_processed)
        data_seq_postition = seq.index(cline[0].strip())
        next_seq_postition = get_next_seq_pos(last_seq_postition, seq)
        while(next_seq_postition != data_seq_postition):
            full_detail[seq[next_seq_postition]].append("   ")
            last_processed = seq[next_seq_postition]
            last_seq_postition = seq.index(last_processed)
            next_seq_postition = get_next_seq_pos(last_seq_postition, seq)
        full_detail[seq[data_seq_postition]].append(" ".join([str(i) for i in cline[1:]]))
        last_processed = seq[data_seq_postition]

data_length = len(full_detail[seq[0]])
for i in range(0,data_length):
    for row in seq:
        print row, full_detail[row][i],
    print

Output

abc 123 456 cde 45 32 efg 322 654公司

abc 445 856 cde 65 21 efg 147 384公司

abc 815 078 cde。电子表格843 286

相关问题 更多 >