[英]Replace the ',' (comma) with a ' ' (space) after every nth element of a list and write it to a text file in python
I have the following question.我有以下问题。
bbox2
is a list of data points, and as you see every bbox2[k - 1::k]
element is 0
. 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')
Now please look at the output. The output I am getting is:现在请看 output。我得到的 output 是:
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.所以现在我的问题是如何像预期的 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.如果我使用另一个
.replace(',0,',',0 ')
那么就会出现问题,因为它正在替换所有它但是我需要在每个bbox2[k - 1::k]
元素之后的空间而不是 a逗号。
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')
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: Output:
126,0,178,38,0 254,415,316,472,0 390,292,423,326,0
You could use while
-loop with bbox2[:k]
and bbox2[k:]
to convert list to 2D list您可以将
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)
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现在您只需要
" ".join()
即可转换为单个字符串
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()
.但是带有
while
-loop 的版本会破坏原始bbox2
并且要保留原始bbox2
你必须用bbox2.copy()
复制它。
Or it is situation when range(len())
can be useful.或者是
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)
It can be use to create useful function slicer()
它可以用来创建有用的 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)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.