我正在编写的代码本质上是一个 super 基本的 AI 系统(基本上是 Cleverbot 的简单 Python 版本)。
作为代码的一部分,我有一个起始字典,其中包含几个以列表作为值的键。当文件运行时,字典会被修改——创建键并将项目添加到关联列表中。
所以我想做的是将字典作为外部文件保存在同一个文件夹中,这样程序就不必在我每次启动文件时“重新学习”数据。所以它会在文件运行开始时加载它,最后它会将新词典保存在外部文件中。我该怎么做?
我必须使用 JSON 来执行此操作吗?如果是,我该怎么做?我可以使用内置的 json 模块来完成,还是需要下载 JSON?我试图查找如何使用它,但找不到任何好的解释。
我的主文件保存在 C:/Users/Alex/Dropbox/Coding/AI-Chat/AI-Chat.py
短语列表保存在C:/Users/Alex/Dropbox/Coding/AI-Chat/phraselist.py
我正在通过 Canopy 运行 Python 2.7。
当我运行代码时,这是输出:
In [1]: %run "C:\Users\Alex\Dropbox\Coding\AI-Chat.py"
File "C:\Users\Alex\Dropbox\Coding\phraselist.py", line 2
S'How are you?'
^
SyntaxError: invalid syntax
编辑:我现在明白了。我必须指定 sys.path 以从 phraselist.py 导入短语
这是我的完整代码:
############################################
################ HELPER CODE ###############
############################################
import sys
import random
import json
sys.path = ['C:\\Users\\Alex\\Dropbox\\Coding\\AI-Chat'] #needed to specify path
from phraselist import phrase
def chooseResponse(prev,resp):
'''Chooses a response from previously learned responses in phrase[resp]
resp: str
returns str'''
if len(phrase[resp])==0: #if no known responses, randomly choose new phrase
key=random.choice(phrase.keys())
keyPhrase=phrase[key]
while len(keyPhrase)==0:
key=random.choice(phrase.keys())
keyPhrase=phrase[key]
else:
return random.choice(keyPhrase)
else:
return random.choice(phrase[resp])
def learnPhrase(prev, resp):
'''prev is previous computer phrase, resp is human response
learns that resp is good response to prev
learns that resp is a possible computer phrase, with no known responses
returns None
'''
#learn resp is good response to prev
if prev not in phrase.keys():
phrase[prev]=[]
phrase[prev].append(resp)
else:
phrase[prev].append(resp) #repeat entries to weight good responses
#learn resp is computer phrase
if resp not in phrase.keys():
phrase[resp]=[]
############################################
############## END HELPER CODE #############
############################################
def chat():
'''runs a chat with Alan'''
keys = phrase.keys()
vals = phrase.values()
print("My name is Alan.")
print("I am an Artifical Intelligence Machine.")
print("As realistic as my responses may seem, you are talking to a machine.")
print("I learn from my conversations, so I get better every time.")
print("Please forgive any incorrect punctuation, spelling, and grammar.")
print("If you want to quit, please type 'QUIT' as your response.")
resp = raw_input("Hello! ")
prev = "Hello!"
while resp != "QUIT":
learnPhrase(prev,resp)
prev = chooseResponse(prev,resp)
resp = raw_input(prev+' ')
else:
with open('phraselist.py','w') as f:
f.write('phrase = '+json.dumps(phrase))
print("Goodbye!")
chat()
phraselist.py 看起来像:
phrase = {
'Hello!':['Hi!'],
'How are you?':['Not too bad.'],
'What is your name?':['Alex'],
}
最佳答案
您可以为此使用pickle
模块。
这个模块有两个方法,
- Pickling(dump):将 Python 对象转换为字符串表示形式。
- Unpickling(load):从存储的字符串表示中检索原始对象。
https://docs.python.org/3.3/library/pickle.html 代码:
>>> import pickle
>>> l = [1,2,3,4]
>>> with open("test.txt", "wb") as fp: #Pickling
... pickle.dump(l, fp)
...
>>> with open("test.txt", "rb") as fp: # Unpickling
... b = pickle.load(fp)
...
>>> b
[1, 2, 3, 4]
以下是我们问题的示例代码:
- 定义短语文件名,并在创建/更新短语数据和获取短语数据期间使用相同的文件名。
- 在获取短语数据期间使用异常处理,即通过
os.path.isfile(file_path)
方法检查文件是否存在于磁盘上。 - 使用
dump
和load
pickle 方法来设置和获取短语。
代码:
import os
import pickle
file_path = "/home/vivek/Desktop/stackoverflow/phrase.json"
def setPhrase():
phrase = {
'Hello!':['Hi!'],
'How are you?':['Not too bad.'],
'What is your name?':['Alex'],
}
with open(file_path, "wb") as fp:
pickle.dump(phrase, fp)
return
def getPhrase():
if os.path.isfile(file_path):
with open(file_path, "rb") as fp:
phrase = pickle.load(fp)
else:
phrase = {}
return phrase
if __name__=="__main__":
setPhrase()
#- Get values.
phrase = getPhrase()
print "phrase:", phrase
输出:
vivek@vivek:~/Desktop/stackoverflow$ python 22.py
phrase: {'How are you?': ['Not too bad.'], 'What is your name?': ['Alex'], 'Hello!': ['Hi!']}
关于python - 在外部文件中保存 Python 字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28572420/