好的每次我重新加载dict()时都会导致项目混乱,因为我试图在dict项目中使用空格。
def load():
dWord = {} # dict
for word in open("Dictionary.DB","r").readlines():
if len(word.strip())>0:
raw = word.split()
word, name, definition, wordtime = ' '.join(raw[0:-3]), raw[1], ' '.join(raw[2:-1]), raw[-1]
dWord[word] = name, definition, int(wordtime)
Dictionary.dWord = dWord
单词和定义使用空格。 def load()之前文件中的内容:
test word charles this is a test 1389611260
在使用def load()之前:
{'test word': ('charles', 'this is a test', 138965430)}
使用def load()之后的示例:
{'test word charles this is': ('word', 'charles this is a test', 1389655439)}
def load()后的文件:
test word charles this is word charles this is a test 1389655469
答案 0 :(得分:2)
看起来您将字典中的字典存储在文本文件中,然后无法正确解析它,因为在保存时会删除重要信息(例如值的开始和结束)。
我建议使用库来保持值的完整性。您应该考虑将JSON用于此类任务,然后您不必自己解析所有内容,仍然可以读取测试文件:
import json
# store your value:
with open('file.txt', 'w') as outFile:
json.dump(dWord, outfile)
# read your value:
with open('file.txt') as inFile:
dword = json.load(inFile)