Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在外部文件中保存Python词典?_Python_Json_Dictionary_Artificial Intelligence - Fatal编程技术网

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

在外部文件中保存Python词典?,python,json,dictionary,artificial-intelligence,Python,Json,Dictionary,Artificial Intelligence,我正在编写的代码本质上是一个超基本的AI系统(基本上是一个简单的Python版本的Cleverbot) 作为代码的一部分,我有一个起始字典,其中有几个键,这些键的值是列表。在文件运行时,将修改字典-创建键并将项添加到关联列表中 因此,我想做的是将字典保存为同一文件夹中的外部文件,这样程序就不必在每次启动文件时“重新学习”数据。因此,它将在开始运行文件时加载它,最后将新字典保存在外部文件中。我该怎么做 我是否必须使用JSON来实现这一点,如果是,我该如何实现?我可以使用内置的json模块,还是需要

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

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

因此,我想做的是将字典保存为同一文件夹中的外部文件,这样程序就不必在每次启动文件时“重新学习”数据。因此,它将在开始运行文件时加载它,最后将新字典保存在外部文件中。我该怎么做

我是否必须使用JSON来实现这一点,如果是,我该如何实现?我可以使用内置的json模块,还是需要下载json?我试图查找如何使用它,但找不到任何好的解释

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

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

phrase = {'Hello!':['Hi!'],'How are you?':['Not too bad.'],
      'What is your name?':['Alex']
     }
我正在运行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从E phraselist.py导入短语

phrase = {'Hello!':['Hi!'],'How are you?':['Not too bad.'],
      'What is your name?':['Alex']
     }
以下是我的完整代码:

############################################
################ 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'],
}

您可以使用
pickle
模块进行此操作。 这个模块有两种方法

  • 酸洗(转储):将Python对象转换为字符串表示形式
  • 取消勾选(加载):从存储的字符串代表中检索原始对象 代码:


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

  • 定义短语文件名,并在创建/更新短语数据和获取短语数据期间使用相同的文件名
  • 在获取短语数据期间使用异常处理,即通过
    os.path.isfile(file\u path)
    方法检查文件是否存在于磁盘上
  • 使用
    dump
    load
    pickle方法设置和获取短语 代码:

    输出:

    vivek@vivek:~/Desktop/stackoverflow$ python 22.py
    phrase: {'How are you?': ['Not too bad.'], 'What is your name?': ['Alex'], 'Hello!': ['Hi!']}
    

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

    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!")
    
    您可以在json中转储它(内置在python中,因此无需安装)


    您可以使用pickle,但该文件将不可读。当您需要存储python(或自定义)对象时,pickle非常有用。

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

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

    不管它是列表、集合、字典还是其他什么。

    为什么不写入另一个Python文件,这样就可以简单地导入为字典?实际上,它需要稍微修改一下。对于您的答案,您必须将其转储并每次加载。对于我来说,您必须加载模块,然后将'phrase='+json.dumps(phrase)输出到文件这本质上类似于pickle,但实际上您可以理解outputpickle使用的存储空间更少;cPickle比pickle快得多这对我来说似乎不起作用。我应该注意到,我正在通过Canopy运行Python2.7(因为我在做一个编程类,他们就是这么用的——我只编写了几个星期)。建议?您看到了什么错误输出?我将用Interpeters的输出编辑我的帖子好的,下面是我现在得到的。当我运行代码时,它会显示%run“C:\Users\Alex\Dropbox\Coding\AI Chat.py”文件“C:\Users\Alex\Dropbox\Coding\phraselist.py”,第2行是“你好吗?”^syntaxer错误:无效语法我仔细检查了两个文件,没有看到任何包含“你好吗?”的部分。为什么Python认为有错误?我编辑了我的原始帖子,以包含我的完整代码。去掉phraselist.py中的任何空白…应该只有一行。这可能会解决您的问题您的代码似乎适合我…(sorta,lol)我将使用运行您粘贴的代码所获得的输出更新我的答案(稍加修改)
    import cPickles as p
    p.dump([Your Data], [Your File])