我正在编写一段代码,它本质上是一个超级基础的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编辑:我现在知道了。我必须指定从phraselist.py导入短语的sys.path
下面是我的完整代码:
############################################
################ 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'],
}发布于 2015-02-18 06:36:16
为此,您可以使用pickle模块。这个模块有两个方法,
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!']}发布于 2015-02-18 06:37:18
你可以把它转储到json中(内置于python中,所以你不需要安装它)。
import json
json.dump(your_dictionary, open('file_name.json', 'wb'))您可以使用pickle,但该文件将不是人类可读的。当您需要存储python (或自定义)对象时,酸洗非常有用。
发布于 2015-02-18 06:36:38
如果您将其存储在同一目录下的文件中,则可以执行以下操作:
phraselist.py
phrase = {'Hello!':['Hi!'],'How are you?':['Not too bad.'],
'What is your name?':['Alex']
}在你的另一个文件中:
from phraselist import phrase然后,您可以根据自己的意愿引用短语。如果你真的想修改这个模块,你可以在整个程序中跟踪这个dict,在你退出之前,把它保存回python文件和它的新内容。也许有一种更优雅的方法可以做到这一点,but...it应该可以工作。
就在您退出之前:
with open('phraselist.py', 'w') as f:
f.write('phrase = '+ json.dumps(phrase))解释器输出:
Python 2.7.3 (default, Sep 26 2013, 20:08:41)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from phraselist import phrase
>>> phrase
{'How are you?': ['Not too bad.'], 'What is your name?': ['Alex'], 'Hello!': ['Hi!']}
>>> phrase['Goodbye'] = ['See you later']
>>> phrase
{'How are you?': ['Not too bad.'], 'What is your name?': ['Alex'], 'Goodbye': ['See you later'], 'Hello!': ['Hi!']}
>>> import json
>>> with open('phraselist.py', 'w') as f:
... f.write('phrase = ' + json.dumps(phrase))
...
>>>
>>> exit()
XXX@ubuntu:~$ python
Python 2.7.3 (default, Sep 26 2013, 20:08:41)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from phraselist import phrase
>>> phrase
{'How are you?': ['Not too bad.'], 'What is your name?': ['Alex'], 'Goodbye': ['See you later'], 'Hello!': ['Hi!']}
>>>你的代码:
phraselist.py:
phrase = {'Hello!':['Hi!'],'How are you?':['Not too bad.'],'What is your name?':['Alex']}运行的输出
XXXX@ubuntu:~$ python AI-Chat.py
My name is Alan.
I am an Artifical Intelligence Machine.
As realistic as my responses may seem, you are talking to a machine.
I learn from my conversations, so I get better every time.
Please forgive any incorrect punctuation, spelling, and grammar.
If you want to quit, please type 'QUIT' as your response.
Hello! hey
Alex what's up?
Not too bad. cool
cool what do you do?
Not too bad. ...okay
what's up? not much, you?
what do you do? I'm a software engineer, what about you?
hey ...hey
not much, you? i'm going to stop now
Alex Goodbye!
i'm going to stop now sigh...
hey QUIT
Goodbye!
XXX@ubuntu:$vi phraselist.py
phrase = {"...okay": [], "not much, you?": ["i'm going to stop now"], "Alex": ["what's up?", "Goodbye!"], "i'm going to stop now": ["sigh..."], "What is your name?": ["Alex"], "Not too bad.": ["cool", "...okay"], "hey": ["...hey"], "...hey": [], "How are you?": ["Not too bad."], "sigh...": [], "what do you do?": ["I'm a software engineer, what about you?"], "what's up?": ["not much, you?"], "Goodb ye!": [], "Hello!": ["Hi!", "hey"], "I'm a software engineer, what about you?": [], "cool": ["what do you do?"]}我在AI-Chat.py中做了一个修改:
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!")https://stackoverflow.com/questions/28572420
复制相似问题