如何将 ctl 文件中的文本垂直连接到水平,然后使用 python 保存在新的 ctl 文件中?

How to concatenate the text from ctl file vertically to horizontally and then save in a new ctl file using python?

我有一个 mlt.ctl 文件,其中的文本排列如下:

 znrmi_001/znrmi_001_001
 znrmi_001/znrmi_001_002
 znrmi_001/znrmi_001_003
 zntoy_001/zntoy_001_001
 zntoy_001/zntoy_001_002
 zntoy_001/zntoy_001_003
 zntoy_001/zntoy_001_004
 .......................
 zntoy_001/zntoy_001_160
 ....................
 zntoy_002/zntoy_002_001
 zntoy_002/zntoy_002_002
 .......................
 zntoy_002/zntoy_002_149

需要在新的mlt.ctl文件中保存需要的格式,需要的格式如下图:

 znrmi_001 znrmi_001_001 znrmi_001_002 znrmi_001_003
 zntoy_001 zntoy_001_001 zntoy_001_002..................zntoy_001_160
 zntoy_002 zntoy_002_001 zntoy_002_002..................zntoy_002_149
 ....................................................................

我在 python 中努力尝试,但每次都遇到错误。

#!/usr/bin/env python

fi= open("mlt.ctl","r")
y_list = []
for line in fi.readlines():
    a1 = line[0:9]
    a2 = line[10:19]
    a3 = line[20:23]
    if a3 in xrange(1,500):
       y = a1+ " ".join(line[20:23].split())
       print(y)
    elif int(a3) < 2:
       fo.write(lines+ "\n")
    else:
       stop
    y_list.append(y)
    print(y)
fi.close()
fo = open ("newmlt.ctl", "w")
for lines in y_list:
    fo.write(lines+ "\n")
fo.close()

我收到 elif 错误,代码不正确 运行,请提供输入。

可能不相关,但你好像忘记了第 11 行的 ')'

 y = a1+ " ".join(line[20:23].split()

应该是

 y = a1+ " ".join(line[20:23].split())

以及第 14 行 else 和第 20 行 for 处的“:”

同样在第 12 行,您可能会比较一个字符串和一个整数

使用正则表达式并将匹配项保存到字典中:

import re

REGEX = r"\d.\s(\S+)/(\S+)" # group 1: the unique index; group 2: the value
finder = re.compile(REGEX) # compile the regular expression

with open('mlt.ctl', 'r') as f:
    data = f.read() # read the entire file into data

matches = re.finditer(finder, data) # find all matches (one for each line)

d = {}
indices = []
for match in matches: # loop through the matches
    key = match.group(1) # the index
    val = match.group(2) # the value

    if key in d.keys(): # the key has already been processed, just append the value to the list
        d[key].append(val)
    else: # the key is new; create a new dict entry and keep track of the index in the indices list
        d[key] = [val]
        indices.append(key)


with open("newmlt.ctl", "w") as out:
    for i, idx in enumerate(indices):
        vals = " ".join(d[idx]) # join the values into a space-delimited string
        to_string = "{} {}\n".format(idx,vals)
        out.write(to_string)

多一点 pythonic:

from collections import defaultdict
d = defaultdict(list)
with open('mlt.ctl') as f:
    for line in f:
        grp, val = line.strip().split('/')
        d[grp].append(val)
with open('newmlt.ctl','w') as f: 
    for k in sorted(d):
        oline = ' '.join([k]+d[k])+'\n'
        f.write(oline)