在列表的每个第 n 个元素之后将 ','(逗号)替换为 ' ' (space),并将其写入 python 中的文本文件

Replace the ',' (comma) with a ' ' (space) after every nth element of a list and write it to a text file in python

我有以下问题。 bbox2 是一个数据点列表,如您所见,每个 bbox2[k - 1::k] 元素都是 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')

现在请查看输出。我得到的输出是:

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

所以现在我的问题是我怎样才能像预期的输出那样编写这个文本文件。

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

如果我使用另一个 .replace(',0,',',0 ') 那么就会出现问题,因为它正在替换所有内容,但我需要在每个 bbox2[k - 1::k] 元素之后使用 space 而不是逗号。

代码如下:

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')
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)

输出:

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

您可以使用 while 循环与 bbox2[:k]bbox2[k:] 将列表转换为二维列表

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)

结果:

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

而这个列表只是简单地转换为字符串列表

substrings = ["DSC07368_053.jpg"]

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

结果:

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

现在你只需要" ".join()转换成单个字符串

result = " ".join(substrings)

结果:

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

完整代码可以缩减为

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)

但是带有 while-loop 的版本会破坏原来的 bbox2 并且要保持原来的 bbox2 你必须用 bbox2.copy().

复制它

或者是range(len())有用的情况。

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)

可以用来创建有用的函数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)

非常感谢所有很棒的解决方案,我也提供了自己的解决方案并且运行良好。我将尝试此线程中给出的解决方案:下面是我的解决方案:

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