如何在输入中输入一个单词,然后让Python在模块中搜索一个名为该变量的变量?

2024-10-03 21:25:00 发布

您现在位置:Python中文网/ 问答频道 /正文

很抱歉标题太长了,但我想不出更好的方式来表达这个。我正在创建一个基本的人工智能程序,我希望它能像字典一样定义单词。现在我将使用python字典,但是我希望数据库在程序完成后保持完整,因此我使用模块的原因。我还希望程序添加到模块,如果单词还没有定义。在

这是我使用的程序的一部分,但我在这一点上卡住了:

from nouns import *
def search():
    try:
        print(nouns.(eval(definer)))
        #This gives me a syntax error
    except NameError:
        define = input("I do not know what this is. Define it for me please: ")
        n = open("nouns.py","a")
        n.write("\n")
        n.write(definer)
        n.write("=")
        n.write("\"")
        n.write(define)
        n.write("\"")
        n.close()
        print("You will have to restart the program before it recognizes the new   definition.")
    asking()

def asking():
    global words
    thewords = input("What do you want to talk about next?\n")
    words = thewords.lower()
    main()

def main():
    global definer

    defining = ("what is a ")
    if defining in words and ("?") in words:
        definerr = str(words[10:-1])
        definer = definerr.lower()
        search()

    defining = ("what is ")
    if defining in words and ("?") in words:
        definerr = str(words[8:-1])
        definer = definerr.lower()
        search()

    defining = ("what is a ")
    if defining in words:
        definerr = str(words[10:])
        definer = definerr.lower()
        search()

    defining = ("what is ")
    if defining in words:
        definerr = str(words[8:])
        definer = definerr.lower()
        search()

asking()

那么,如何在输入中键入一个单词,然后让python搜索一个名为该变量的单词,最后让python在原始程序中打印该变量?在


Tags: in程序searchifis单词lowerwhat
2条回答

开始使用json模块和内存中的dict编辑的一些代码:

#!/usr/bin/env python

import json
import os

FILE = "defs.json"

# load file (if exists...)
if not os.path.exists(FILE):
    defs = {}
else:
    with open(FILE) as defs_file:
        try:
            defs = json.load(defs_file)
        except ValueError:
            # invalid file - replace it with valid empty file
            defs = {}

# do stuff...    
defs['new definition'] = 'new value'

# save dict to the file
with open(FILE, 'w') as defs_file:
    json.dump(defs, defs_file)

您需要将对象存储在文件或类似的文件中。如果您希望您的字典可以从应用程序外部进行编辑,我建议使用json,如果您希望它只在应用程序中可编辑,请使用pickle。我将给出一个json示例:

在单词.json公司名称:

{
    'thing': 'some object'
}

Python:

^{pr2}$

相关问题 更多 >