【发布时间】:2015-02-17 22:32:25
【问题描述】:
我正在编写一个本质上是超级基础人工智能系统的代码(基本上是一个简单的 Python 版本的 Cleverbot)。
作为代码的一部分,我有一个起始字典,其中包含几个以列表作为值的键。在文件运行时,字典会被修改 - 创建键并将项目添加到关联列表中。
所以我想做的是将字典作为外部文件保存在同一个文件夹中,这样程序就不必在每次启动文件时“重新学习”数据。所以它会在开始运行文件时加载它,最后它将新字典保存在外部文件中。我该怎么做?
我是否必须使用 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 才能从短语列表.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'],
}
【问题讨论】:
-
为什么不写入另一个 Python 文件,以便您可以简单地作为字典导入?
标签: python json dictionary artificial-intelligence