在这里插入代码片
分两个部分,读取以及添加txt内容。
效果图如下:以字典形式保存,并读出标签存为list,摆脱’\n’等字符影响。然后可以继续向量间的余弦距离,执行完后,可以追加保存新标签以及向量。
全部代码:
import numpy as np
path = r'E:/sign_system/execute_system/crop_feature/ff.txt'
f = open(path,'r')
cur_entry = {}
numlist = []
namelist = []
while True:
line = f.readline().strip('\n') # 以行的形式进行读取文件
if not line:
break
names = line
namelist.append(names)
for i in range(5):
nums = f.readline().strip('\n').split(' ')
for j in nums:
try:
float(j)
numlist.append(float(j))
except ValueError:
pass
#cur_entry[]=list1
cur_entry[names] = numlist
numlist = []
print(cur_entry)
print(namelist)
f.close()
'''找出最大余弦值'''
old = (116.05824203,15.36411934,-10.23096142 ,27.85675507 , -16.82574615,
-11.50386963 , -45.92348251 , -36.17513504, 45.63838692 , -89.19012756,
134.94717102 ,-196.72629395 , 25.11620178 , 205.47620544 , -44.02067566,
-15.20974121 , -57.71832199 , 377.6208374 , 32.38473549 , -52.72783813,
-16.74344716 , -42.26617355 , 110.0730113)
d1 = 0
show_name = ''
for n,v in cur_entry.items():
v = np.array(v)
#print(n,v)
d=np.dot(v,old)/(np.linalg.norm(v)*np.linalg.norm(old))
print(d)
if d > d1:
d1 = d
show_name = str(n)
else:
pass
print(show_name)
'''存向量以及名字'''
ssname = input('请输入名字: ')
path = r'E:/sign_system/execute_system/crop_feature/ff.txt'
f = open(path,'r')
olddad = (116.05824203,15.36411934,-10.23096142 ,27.85675507 , -16.82574615,
-11.50386963 , -45.92348251 , -36.17513504, 45.63838692 , -89.19012756,
134.94717102 ,-196.72629395 , 25.11620178 , 205.47620544 , -44.02067566,
-15.20974121 , -57.71832199 , 377.6208374 , 32.38473549 , -52.72783813,
-16.74344716 , -42.26617355 , 110.0730113)
cur_entry = {}
numlist = []
namelist = []
while True:
line = f.readline().strip('\n') # 以行的形式进行读取文件
if not line:
break
names = line
namelist.append(names)
for i in range(5):
nums = f.readline().strip('\n').split(' ')
numlist.append(nums)
numlist = []
print(namelist)
f.close()
olddad = np.array(olddad)
if ssname not in namelist:
fw = open(path,'a')
fw.write('\n')
fw.write(ssname)
fw.write('\n')
fw.write(str(olddad))
fw.close()
建议采用如下存取方式,主要考虑到浮点数有长短
count = 0
for element in olddad.flat:
count = count + 1
f.write(str(element))
f.write(’ ‘)
if int(count%5) ==0:
f.write(’\n’)
f.close()