将Python字典保存在外部文件中吗? [英] Saving a Python dictionary in external file?

查看:96
本文介绍了将Python字典保存在外部文件中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写本质上是超基本AI系统(基本上是Cleverbot的简单Python版本)的代码.

I'm working on a code that is essentially a super basic AI system (basically a simple Python version of Cleverbot).

作为代码的一部分,我有一个带有几个键的起始字典,这些键具有列表作为值.在文件运行时,将修改字典-创建键并将项目添加到关联的列表中.

As part of the code, I've got a starting dictionary with a couple keys that have lists as the values. As the file runs, the dictionary is modified - keys are created and items are added to the associated lists.

所以我要做的是将字典另存为外部文件,并且保存在同一文件夹中,这样程序不必在每次启动文件时都重新学习"数据.因此它将在运行文件的开始时加载它,并在最后将新字典保存在外部文件中.我该怎么办?

So what I want to do is have the dictionary saved as an external file in the same file folder, so that the program doesn't have to "re-learn" the data each time I start the file. So it will load it at the start of running the file, and at the end it will save the new dictionary in the external file. How can I do this?

我必须使用JSON进行此操作吗?如果是,该怎么做?我可以使用内置的json模块执行此操作,还是需要下载JSON?我试图查找如何使用它,但找不到真正好的解释.

Do I have to do this using JSON, and if so, how do I do it? Can I do it using the built-in json module, or do I need to download JSON? I tried to look up how to use it but couldn't really find any good explanations.

我的主文件保存在C:/Users/Alex/Dropbox/Coding/AI-Chat/AI-Chat.py

I have my main file saved in C:/Users/Alex/Dropbox/Coding/AI-Chat/AI-Chat.py

短语列表保存在C:/Users/Alex/Dropbox/Coding/AI-Chat/phraselist.py

The phraselist is saved in C:/Users/Alex/Dropbox/Coding/AI-Chat/phraselist.py

我正在通过Canopy运行Python 2.7.

I'm running Python 2.7 through Canopy.

运行代码时,这是输出:

When I run the code, this is the output:

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

I got it now. I had to specify the sys.path to import phrase 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()

短语列表.py如下:

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

推荐答案

您可以为此使用pickle模块. 该模块有两种方法,

You can use pickle module for that. This module have two methods,

  1. 酸洗(转储):将Python对象转换为字符串表示形式.
  2. 解开(加载):从存储的字符串表示中检索原始对象.
  1. Pickling(dump): Convert Python objects into string representation.
  2. Unpickling(load): Retrieving original objects from stored string representstion.

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]


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


Following is sample code for our problem:

  1. 在创建/更新短语数据以及获取短语数据期间,定义短语文件名并使用相同的文件名.
  2. 在获取短语数据期间使用异常处理,即通过os.path.isfile(file_path)方法检查磁盘上是否存在文件.
  3. 因为使用dumpload泡菜方法来设置和获取短语.
  1. Define phrase file name and use same file name during create/update phrase data and also during get phrase data.
  2. Use exception handling during get phrase data i.e. check if file is present or not on disk by os.path.isfile(file_path) method.
  3. As use dump and load pickle methods to set and get phrase.

代码:

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字典保存在外部文件中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆