[英]Dictionary is being 'appended' and printed randomly
好吧,在我問之前,我已經看到了以下答案:
但我仍然無法做到這一點。
背景:我在某個路徑下有一個groundtruth文件,例如jp1_GT.txt(在其他路徑下也有其他文件,但目前我只關心一個文件)。 在此文件中,每一行均以格式表示一個邊界框。 我正在通過一些計算來更改,並打算將它們寫入新的groundtruth文件中。
#Path containing old folders
src_path = r"C:\Users\username\Downloads\LITIV_dataset"
#dictionary creation
newgtdict ={}
for folderName in os.listdir(src_path):
folderPath = src_path + "\\" + folderName
if not os.path.isdir(folderPath):
continue
listOfFilePaths = glob.glob(folderPath + "\\"+ folderName +"_GT.txt")
for filePath in listOfFilePaths:
openedFile = open(filePath, 'r')
lines = openedFile.readlines()
linecount =0
for line in lines:
linecount+=1
linenumber = str(linecount)
my_list = str(line).split(",")
bboxes=[]
#checking for non-empty lines
if len(my_list)>0:
x_br = int(my_list[2])
y_br = int(my_list[3])
x_tl = int(my_list[0]) - (x_br/2)
y_tl = int(my_list[1]) - (y_br/2)
box = [x_tl,y_tl,x_br,y_br]
newgtdict[str(filePath)+str(linenumber)] = box
print newgtdict
我的jp1_GT.txt的前四行如下所示:
189,163,72,72
190,162,72,72
188,160,72,72
189,163,72,72
但是,輸出的前四行如下所示:
{'C:\\Users\\username\\Downloads\\LITIV_dataset\\jp1\\jp1_GT.txt1': [153, 127, 72, 72]}
{'C:\\Users\\username\\Downloads\\LITIV_dataset\\jp1\\jp1_GT.txt1': [153, 127, 72, 72], 'C:\\Users\\username\\Downloads\\LITIV_dataset\\jp1\\jp1_GT.txt2': [154, 126, 72, 72]}
{'C:\\Users\\username\\Downloads\\LITIV_dataset\\jp1\\jp1_GT.txt1': [153, 127, 72, 72], 'C:\\Users\\username\\Downloads\\LITIV_dataset\\jp1\\jp1_GT.txt3': [152, 124, 72, 72], 'C:\\Users\\username\\Downloads\\LITIV_dataset\\jp1\\jp1_GT.txt2': [154, 126, 72, 72]}
{'C:\\Users\\username\\Downloads\\LITIV_dataset\\jp1\\jp1_GT.txt4': [153, 127, 72, 72], 'C:\\Users\\username\\Downloads\\LITIV_dataset\\jp1\\jp1_GT.txt1': [153, 127, 72, 72], 'C:\\Users\\username\\Downloads\\LITIV_dataset\\jp1\\jp1_GT.txt3': [152, 124, 72, 72], 'C:\\Users\\username\\Downloads\\LITIV_dataset\\jp1\\jp1_GT.txt2': [154, 126, 72, 72]}
預期的前4行輸出:
{'C:\\Users\\username\\Downloads\\LITIV_dataset\\jp1\\jp1_GT.txt1': [153, 127, 72, 72]}
{'C:\\Users\\username\\Downloads\\LITIV_dataset\\jp1\\jp1_GT.txt2': [154, 126, 72, 72]}
{'C:\\Users\\username\\Downloads\\LITIV_dataset\\jp1\\jp1_GT.txt3': [152, 124, 72, 72]}
{'C:\\Users\\username\\Downloads\\LITIV_dataset\\jp1\\jp1_GT.txt4': [153, 127, 72, 72]}
只是一個附帶的問題:您是否提出其他更好的方法?
您將在每次迭代中打印字典,而不是在每次迭代中將新項目打印到字典中。
您可以這樣做:
for line in lines:
# <snip>
newgtdict[str(filePath)+str(linenumber)] = box
print box
要么
for line in lines:
# <snip>
newgtdict[str(filePath)+str(linenumber)] = box
# don't print here
for line in newgtdict:
print(line)
請注意,您沒有使用OrderedDict,而應該使用(如果要在3.7之前的Python版本中使用有序結果)
newgtdict = collections.OrderedDict()
# rather than = {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.