1

I have the following question. bbox2 is a list of data points, and as you see every bbox2[k - 1::k] element is 0.

save_text = [image_path]
bbox2 = [126,0,178,38,0,254,415,316,472,0,390,292,423,326,0]
bbox2 = str(bbox2).replace(' ', '')
save_text.append(bbox2)
with open('output.txt', 'a') as file:
               file.write(' '.join(map(str, save_text)).replace('[', '').replace(']', '') + '\n')

Now please look at the output. The output I am getting is:

output:
DSC07368_053.jpg 126,0,178,38,0,254,415,316,472,0,390,292,423,326,0

So now my question is how can I write this text file like the expected output.

Expected output:
DSC07368_053.jpg 126,0,178,38,0 254,415,316,472,0 390,292,423,326,0

If I use another .replace(',0,',',0 ') then there is a problem because it is replacing all of it but I need the space after each bbox2[k - 1::k] element instead of a comma.

Sony
  • 55
  • 1
  • 5
  • Iterate over list in batches of 5 elements and convert each batch to comma-separated string. I must say that the output looks odd and mat be tricky to work with afterwards – buran Feb 25 '22 at 13:15
  • Would you be kind to elaborate on the answer? I mean how can I do it efficiently. Thanks in advance – Sony Feb 25 '22 at 13:19
  • Check https://stackoverflow.com/q/434287/4046632 – buran Feb 25 '22 at 13:23
  • it could be simpler to run loop which gets `bbox2[:k]` and rest assign to the same variable `bbox2 = bbox2[k:]` - this way you can create 2D list `[ [126,0,178,38,0] , [254,415,316,472,0] , [390,292,423,326,0] ]` and this list it is simpler to convert to list with strings [ "126,0,178,38,0" , "254,415,316,472,0" , "390,292,423,326,0" ]` (using `",".join()` , and later you can use `" ".join()` to convert list of strings to single string. – furas Feb 25 '22 at 20:10

4 Answers4

0

Following is the code :

save_text = ["FileName"]
bbox2 = [126,0,178,38,0,254,415,316,472,0,390,292,423,326,0]
bbox2 = str(bbox2).replace(' ', '')
bbox2 = bbox2.replace('[','').replace(']','')
print(bbox2)

count = 0
IndexOfEveryFifthComma = []
Commas = []
for each in bbox2:

    count = count + 1
    if each == ',':
       Commas.append(each)
       if len(Commas) % 5 == 0:
            IndexOfEveryFifthComma.append(count-1)

print(Commas)
print(IndexOfEveryFifthComma)

bbox2_list = list(bbox2)

for each in IndexOfEveryFifthComma:
    bbox2_list[each] = ' '

bbox2 = ''.join(bbox2_list)
print(bbox2)

save_text.append(bbox2)
with open('output.txt', 'a') as file:
              file.write(' '.join(map(str, save_text)).replace('[', '').replace(']', '') + '\n')
0
bbox2 = [126,0,178,38,0,254,415,316,472,0,390,292,423,326,0]
k = 5
output = ""
for index,item in enumerate(bbox2):
    if index % k == 0:
        output += " "
    else:
        output += ","
    output += str(item)
output = output.strip()
print(output)

Output:

126,0,178,38,0 254,415,316,472,0 390,292,423,326,0
Leo Eiji
  • 54
  • 6
0

You could use while-loop with bbox2[:k] and bbox2[k:] to convert list to 2D list

bbox2 = [126,0,178,38,0,254,415,316,472,0,390,292,423,326,0]

k = 5

list2D = []

while bbox2:
    list2D.append(bbox2[:k])  # beginnig elements
    bbox2 = bbox2[k:]         # rest of list

print(list2D)

Result:

[ 
   [126, 0, 178, 38, 0], 
   [254, 415, 316, 472, 0], 
   [390, 292, 423, 326, 0]
]

And this list is simply to convert to list of strings

substrings = ["DSC07368_053.jpg"]

for sublist in list2D:
    text = ",".join( map(str, sublist) )
    substrings.append(text)
    
print(substrings)   

Result:

[ "DSC07368_053.jpg", "126,0,178,38,0",  "254,415,316,472,0", "390,292,423,326,0" ]

And now you need only " ".join() to convert to single string

result = " ".join(substrings)

Result:

DSC07368_053.jpg 126,0,178,38,0 254,415,316,472,0 390,292,423,326,0

Full code can be reduced to

bbox2 = [126,0,178,38,0,254,415,316,472,0,390,292,423,326,0]

k = 5

substrings = ["DSC07368_053.jpg"]

while bbox2:
    sublist = bbox2[:k]  # beginnig elements
    bbox2 = bbox2[k:]    # rest of list

    text = ",".join( map(str, sublist) )
    substrings.append(text)
    
result = " ".join(substrings)

print(result)

But version with while-loop destroys original bbox2 and to keep original bbox2 you would have to duplicate it with bbox2.copy().

Or it is situation when range(len()) can be useful.

bbox2 = [126,0,178,38,0,254,415,316,472,0,390,292,423,326,0]

k = 5

substrings = ["DSC07368_053.jpg"]

for x in range(0, len(bbox2), k):
    sublist = bbox2[x:x+k]
    text = ",".join(map(str, sublist))
    substrings.append(text)
    
result = " ".join(substrings)

print(result)

It can be use to create useful function slicer()

def slicer(data, k):
    for x in range(0, len(data), k):
        yield data[x:x+k]
    
# ---

bbox2 = [126,0,178,38,0,254,415,316,472,0,390,292,423,326,0]

k = 5

substrings = ["DSC07368_053.jpg"]

for sublist in slicer(bbox2, k):
    text = ",".join(map(str, sublist))
    substrings.append(text)
    
result = " ".join(substrings)

print(result)
furas
  • 134,197
  • 12
  • 106
  • 148
0

Thanks a lot for all the awesome solutions, I also come with my own solution and it is working fine. I will try the solutions given in this thread: Below was my solution:

def replace_comma(bbox2, image_path):
    start = 0
    text = ""
    for idx in range(len(bbox2) + 1):
        if idx % 5 == 0 and idx != 0:
            next = idx
            val = str(bbox2[start:next]).replace(" ", "")
            text = f"{text} {val}"
            start = next

    text = text.replace("[", "").replace("]", "").strip()
    save_text = f"{image_path} {text}\n"
    return save_text
Sony
  • 55
  • 1
  • 5