我正在编写的代码本质上是一个超级基本的人工智能系统(基本上是 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 来导入短语 fromephraselist.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'],
}