我有一个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错误并且代码运行不正常,请提供输入。
答案 0 :(得分:1)
使用正则表达式并将匹配保存到字典:
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)
答案 1 :(得分:1)
多一点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)
答案 2 :(得分:0)
也许它没有关联,但似乎你忘记了一个&#39;)&#39;在第11行
y = a1+ " ".join(line[20:23].split()
应该是
y = a1+ " ".join(line[20:23].split())
和&#39;:&#39;在第14行的else
和第20行的for
同样在第12行,您可能会比较一个字符串和一个整数