gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:19:45 24 4
gpt4 key购买 nike

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

需要在newmlt.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 错误,代码未正常运行,请提供输入。

最佳答案

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

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)

关于python - 如何使用python将ctl文件中的文本垂直连接到水平然后保存在新的ctl文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42037573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com