我有以下文本文件:
0 something 0.008
0 something2 0.004
0 something3 0.003
0 something4 0.001
0 something5 0.000
1 something 0.008
1 something2 0.004
1 something3 0.003
1 something4 0.001
1 something5 0.000
以及下面的代码读取文件,并且仅占用从0开始的前3行,从1开始的前3行,依此类推。到目前为止,除了最后添加浮点数(在代码中标记为w)之外,它都成功地完成了这一任务,由于强制转换,我很难添加它。
with open('output.txt', mode = 'r') as f:
MAX = 3
i = 0
weight=0
output = []
while True:
line = f.readline().strip()
if line == '':
break
line = line.split()
i = int(line[0])
w=float(line[2]) # I want to add this at the end of every line as well
try:
output[i]
except IndexError:
for i in range(len(output), i + 1):
output.append([])
if len(output[i]) < MAX:
output[i].append(line[1])
for i, j in enumerate(output):
print(i, *j)
所需的输出:
0 something 0.008 something2 0.004 something3 0.003
1 something 0.00 something2 0.004 something3 0.003
如何添加它?提前非常感谢您!
答案 0 :(得分:2)
读取文件的每一行,然后将每一行数据添加到collections.defaultdict()
中,确保每一行的第一项是分组密钥,然后仅从每一行中提取[:3]
最后分组:
from collections import defaultdict
d = defaultdict(list)
with open("test.txt") as f:
for line in f:
key, *rest = line.split()
d[key].append(rest)
for k, v in d.items():
print("%s %s" % (k, " ".join("%s %s" % (x, y) for x, y in v[:3])))
哪些输出:
0 something 0.008 something2 0.004 something3 0.003
1 something 0.008 something2 0.004 something3 0.003
答案 1 :(得分:1)
您只需使用str(w)即可将其转换为字符串
with open('output.txt', mode = 'r') as f:
MAX = 3
i = 0
weight=0
output = []
while True:
line = f.readline().strip()
if line == '':
break
line = line.split()
print("line ",line)
i = int(line[0])
w=float(line[2]) # I want to add this at the end of every line as well
try:
output[i]
except IndexError:
for i in range(len(output), i + 1):
output.append([])
if len(output[i]) < MAX:
output[i].append(line[1]+" "+str(w))
for i, j in enumerate(output):
print(i, j)