I have a text file in this format:
JavaScript
x
5
1
0.jpg 12,13,14,15,16
2
0.jpg 13,14,15,16,17
3
1.jpg 1,2,3,4,5
4
1.jpg 2,3,4,5,6
5
I want to check if the image name is the same and then concatenate those lines into one line with the following format:
JavaScript
1
3
1
0.jpg 12,13,14,15,16 13,14,15,16,17
2
1.jpg 1,2,3,4,5 2,3,4,5,6
3
I have tried something like this but don’t know how to do the actual comparison and also don’t quite know what logic to apply since the first line_elements[0]
will be taken and compared with each other line’s line_elements[0]
JavaScript
1
16
16
1
with open("file.txt", "r") as input: # Read all data lines.
2
data = input.readlines()
3
with open("out_file.txt", "w") as output: # Create output file.
4
for line in data: # Iterate over data lines.
5
line_elements = line.split() # Split line by spaces.
6
line_updated = [line_elements[0]] # Initialize fixed line (without undesired patterns) with image's name.
7
if line_elements[0] = (next line's line_elements[0])???:
8
for i in line_elements[1:]: # Iterate over groups of numbers in current line.
9
tmp = i.split(',') # Split current group by commas.
10
if len(tmp) == 5:
11
line_updated.append(','.join(tmp))
12
13
if len(line_updated) > 1: # If the fixed line is valid, write it to output file.
14
output.write(f"{' '.join(line_updated)}n")
15
16
Could be something like:
JavaScript
1
12
12
1
for i in range (len(data)):
2
if line_elements[0] in line[i] == line_elements[0] in line[i+1]:
3
4
line_updated = [line_elements[0]]
5
for i in line_elements[1:]: # Iterate over groups of numbers in current line.
6
tmp = i.split(',') # Split current group by commas.
7
if len(tmp) == 5:
8
line_updated.append(','.join(tmp))
9
10
if len(line_updated) > 1: # If the fixed line is valid, write it to output file.
11
output.write(f"{' '.join(line_updated)}n")
12
Advertisement
Answer
Save the first field of the line in a variable. Then check if the first field of the current line is equal to the value. If it is, append to the value, otherwise write the saved line and start a new output line.
JavaScript
1
15
15
1
current_name = None
2
3
with open("out_file.txt", "w") as output:
4
for line in data:
5
name, values = line.split()
6
if name == current_name:
7
current_values += ' ' + values
8
continue
9
if current_name:
10
output.write(f'{current_name} {current_values}n')
11
current_name, current_values = name, values
12
# write the last block
13
if current_name:
14
output.write(f'{current_name} {current_values}n')
15