Сделайте словарь как вводимый пользователем, затем сохраните его в файл json - PullRequest
2 голосов
/ 27 мая 2020

Я пытаюсь создать базу словарей, как настоящий словарь. Пользователь вводит ключевое слово и значение, и программа сохраняет его в базе данных. Как вводное слово: дождь, введите значение слова: капли воды падают с облаков, затем программа сделает его словарем. Пока я могу это сделать, но это не работает так, как я хочу.

class Mydictionary:
    def __init__(self):
        self.key=input("Please input word: ")
        self.value=input("Please input meaning of the word: ")

    def mydictionary(self):
        self.dic={self.key:self.value}

Mydic=Mydictionary()
Mydic.mydictionary()

Работает только один раз. Я хочу сохранять столько ключевых слов и значений, сколько хочу. Я хочу создать словарную базу данных.

Ответы [ 4 ]

1 голос
/ 27 мая 2020

Чтобы вставить новую пару key - value в ваш словарь, вам необходимо создать метод для получения данных от пользователя.

В __init__ вы можете объявить пустой словарь, а затем в insert метод, вы можете получить новую запись от пользователя.

Более того, для отображения текущих элементов словаря вы можете создать отдельный метод с именем display.

json встроенный может напрямую записывать и читать данные типа словаря из файла json. Вы можете прочитать о json из официальной документации на json.

import json
import os


class Mydictionary:
    def __init__(self, file_name):
        self.json_file = file_name
        if os.path.exists(file_name):
            with open(self.json_file, "r") as json_output:
                self.data = json.load(json_output)
        else:
            self.data = {}


    def insert(self):
        user_key = input("Please input word: ")
        user_value = input("Please input meaning of the word: ")
        self.data[user_key] = user_value
        with open(self.json_file, "w") as json_output:
            json.dump(self.data, json_output)

    def display(self):
        if os.path.exists(self.json_file):
            with open(self.json_file, "r") as json_output:
                print(json.load(json_output))
        else:
            print("{} is not created yet".format(self.json_file))

Mydic=Mydictionary("data.json")
Mydic.display()
Mydic.insert()
Mydic.insert()
Mydic.display()

Вывод:

data.json is not created yet
Please input word: rain
Please input meaning of the word: water droplets falling from the clouds
Please input word: fire
Please input meaning of the word: Fire is a chemical reaction that releases light and heat
{'rain': 'water droplets falling from the clouds', 'fire': 'Fire is a chemical reaction that releases light and heat'}

Отказ от ответственности : Это это просто концепция объявления и использования классов и методов. Вы можете импровизировать этот подход.

1 голос
/ 27 мая 2020

enter image description here

Насколько я мог видеть, он работает отлично, как вы объяснили ...

Если бы вы думали, что хотите вставить много значений в одном объекте, это не сработает, поскольку вы получаете только один ввод при вызове конструктора.

Вы должны реализовать это как:

import json

class Mydictionary:
    def __inint__(self):
        self.dic = {}

    def mydictionary(self):
        self.key=input("Please input word: ")
        self.value=input("Please input meaning of the word: ")
        self.dic[self.key] = self.value

    def save(self, json_file):
        with open(json_file, "w") as f:
            json.dump(self.dic, f)

Mydic=Mydictionary()
Mydic.mydictionary()
Mydic.mydictionary()

# to save it in a JSON file
Mydic.save("mydict.json")

Теперь вы можете вызовите метод n раз, чтобы добавить n записей ...

Вы можете посмотреть ответ @arsho ниже, который я считаю хорошей практикой. Очень важно присвоить функции имя, соответствующее фактической функции, которую она выполняет.

0 голосов
/ 27 мая 2020
class dictionary():
    def __init__(self):
        self.dictionary={}

    def insert_word(self,word):
        self.dictionary.update(word)

    def get_word(self):
        word=input("enter a word or enter nothing to exit: ")
        if word=="":
            return None
        meaning=input("enter the meaning: ")
        return {word:meaning}

    def get_dict(self):
        return self.dictionary


if __name__ == "__main__":
    mydict=dictionary()
    word=mydict.get_word()
    while word:
        mydict.insert_word(word)
        word=mydict.get_word()
    print(mydict.get_dict())

это будет продолжать принимать входные данные, пока вы не дадите ему нулевое значение, а затем распечатаете словарь, когда вы остановитесь.

0 голосов
/ 27 мая 2020

Попробуйте:

import json

class MyDictionary:

    __slots__ = "dic",

    def __init__(self):
        self.dic = {}

    def addvalue(self):
        """Adds a value into the dictionary."""
        key=input("Please input word: ")
        value=input("Please input meaning of the word: ")
        self.dic[key] = value

    def save(self, json_file):
        """Saves the dictionary into a json file."""
        with open(json_file, "w") as f:
            json.dump(self.dic, f)

# Testing

MyDic = MyDictionary()
MyDic.addvalue()
MyDic.addvalue()

print(MyDic.dic) # Two elements
MyDic.save("json_file.json") # Save the file
...