【发布时间】:2020-05-07 19:40:15
【问题描述】:
完整的python新手,使用python 3.6并希望有人能够提供帮助,我正在尝试从darknet/yolo获取输出,并将其与文件中保存的先前命令输出进行比较。我认为我正在错误地写入或读取文件中的列表,因为从文件中读取时我得到了额外的方括号和引号:
["['tvmonitor', 'person']"]
任何尝试使用 [1:-1] 读取变量来修剪变量都会完全清除内容,因此假定它将正在读取的数据计为一项。
我从检测对象的 darknet/yolo 获取输出并返回一个对象列表,该列表被标记为字节,然后我将其解码为 utf-8。
带有输出的示例代码(请参阅 # cmets -- 如果格式不正确,请见谅)
# define a few things to be used later
lastsaw = []
olditem = []
# r is a dummy of the output from darknet
r = [b'tvmonitor', b'chair']
print ("this is r")
print (r)
print (type(r))
#output from above code block
# this is r
# [b'tvmonitor', b'chair']
# <class 'list'>
# decode r as utf-8
seenitem = [listitem.decode('utf-8') for listitem in r]
print ("this is seenitem")
print (seenitem)
print (type(seenitem))
# output from above code block:
# this is seenitem
# ['tvmonitor', 'chair']
# <class 'list'>
# read previous runs darknet output in to lastsaw variable
# contents of file is
# ['tvmonitor', 'person']
with open("lastsaw.txt", "r") as filehandle:
filecontents = filehandle.readlines()
olditem = (line for line in filecontents)
lastsaw.extend(olditem)
filehandle.close()
print ("this is lastsaw")
print (lastsaw)
print (type(lastsaw))
# output from above code block (was expecting ['tvmonitor', 'person'] ):
# this is lastsaw
# ["['tvmonitor', 'person']"]
# <class 'list'>
# diff the two lists against each other to find what is missing and what has been added
def Diff(lastsaw, seenitem):
sawseen = (list(set(lastsaw) - set(seenitem)))
print("This has gone::>")
print (Diff(lastsaw, seenitem))
# output from above code block (was expecting 'person'] returned):
# This has gone::>
# None
def Diff(seenitem, lastsaw):
seensaw = (list(set(seenitem) - set(lastsaw)))
print("This is new::>")
print (Diff(seenitem, lastsaw))
# output from above code block (was expecting ['chair'] returned):
# This is new::>
# None
欣赏任何见解
已编辑 -- 抱歉无法添加到 cmets,但被询问列表是如何保存到文件的。保存“r”列表的代码(即暗网输出):
这是我调用暗网的部分,将捕获的图像传递给它,我试图在写入之前从字节解码它
#call darknet
if os.path.isfile("/images/img_.jpg"):
r = (darknet.detect(net, meta, (bytes("/images/img_.jpg", encoding='utf-8'))))
f= open(b"/output/dknet.txt","w+")
seenitem = [listitem.decode('utf-8') for listitem in r]
f.write ('%s' % seenitem)
f.close ()
稍后在脚本中,我将新文件复制到之前的文件中,以便下次运行时使用 lastsaw.txt
【问题讨论】:
-
最好使用
with open('my_file.json', 'w+') as f:和json.dump(f, my_lst_or_dict)将数据保存为json。 (我可能手头有参数,扩展名可以是任何东西)。 -
我上面推荐中的
.dump()参数是倒退的,对象先行,然后是文件处理程序。
标签: python-3.x