我正在使用一个函数来计算某些哈希方法的标准偏差,但我似乎无法从列表中读取单词,而列表又通过索引到字符串的第一个字母来从文件中加载单词以下是整个代码:
import numpy as np
listhash1=[]
listhash2=[]
listhash3=[]
templist=[]
dictlist=[]
def hash1(list:list,list1):
for i in range(len(list)):
list1.append(ord((list[i][0]).upper())+len(list[i])-ord('A'))
return list1
def hash2(list:list,list2):
for i in range(len(list)):
list2(((ord((list[i][0]).upper())-ord('A'))*len(list[i]))%100)
def hash3(list:list,list3):
for i in range(len(list)):
list3((ord((list[i][0]).upper())-ord('A'))%len(list[i]))
def variance(list):
sum=0
deviations=0
for i in range(len(list)):
sum=sum+list[i]
sum=sum/len(list)
for j in range(len(list)):
deviations=deviations+np.pow((list[j]-sum),2)
deviations=deviations/len(list)
deviations=np.pow(deviations,0.5)
return deviations
q=0
with open("dict.txt","r") as dictionary:
for line in dictionary:
dictlist.append(dictionary.readline())
listhash1=hash1(dictlist,templist)
listhash2=hash2(dictlist,templist)
listhash3=hash3(dictlist,templist)
print(variance(listhash1),"\n",variance(listhash2),"\n",variance(listhash3),"\n")
很抱歉缺乏具体性,这是我在这个网站上的第一个问题
看来您实际上并没有反序列化
dict
对象,而只是将其(逐行)作为文件读取:
with open("dict.txt","r") as dictionary:
for line in dictionary:
dictlist.append(dictionary.readline())
你可以尝试这样的事情:
import ast
with open("dict.txt","r") as dictionary:
dictlist = ast.literal_eval(dictionary.read())
这是对您想要做什么的有根据的猜测。但不知何故,你需要将文件对象(或文本)放入Python对象(dict)中。