在外部文件中保存Python字典?

时间:2015-02-17 22:32:25

标签: python json dictionary artificial-intelligence

我正在开发一个基本上是超级基本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来导入短语frome 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'],
}

4 个答案:

答案 0 :(得分:4)

您可以使用pickle模块。 该模块有两种方法,

  1. 腌制(转储):将Python对象转换为字符串表示形式。
  2. 取消(加载):从存储的字符串表示中检索原始对象。
  3. 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]
    

    以下是我们问题的示例代码:

    1. 定义短语文件名,并在创建/更新短语数据期间以及获取短语数据期间使用相同的文件名。
    2. 在获取短语数据期间使用异常处理,即通过os.path.isfile(file_path)方法检查磁盘上是否存在文件。
    3. 使用dumpload pickle方法来设置和获取短语。
    4. 代码:

      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!']}
      

答案 1 :(得分:3)

你可以把它转储到json中(内置到python中,所以你不需要安装它)

import json 
json.dump(your_dictionary, open('file_name.json', 'wb'))

你可以使用泡菜,但文件不会是人类可读的。当您需要存储python(或自定义)对象时,Pickling非常有用。

答案 2 :(得分:0)

如果您将其存储在同一目录中的文件中,则可以执行以下操作:

phraselist.py

phrase = {'Hello!':['Hi!'],'How are you?':['Not too bad.'],
      'What is your name?':['Alex']
     }

并在您的其他文件中执行:

from phraselist import phrase

然后您可以根据需要引用短语。如果你真的想要修改模块,你可以在整个程序中跟踪dict,在退出之前,将其保存回python文件及其新内容。可能有更优雅的方式来做到这一点,但......它应该有效。

退出前

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!")

答案 3 :(得分:0)

使用cPickles,它可以将任何python结构存储到文件

import cPickles as p
p.dump([Your Data], [Your File])

无论是列表,集合,字典还是其他什么。