简体   繁体   English

如何将文本文件转换为要在 Python 中使用的字典?

[英]How can I convert a text file to a dictionary to be used in Python?

I am doing a small programming project for school, one of the main elements of my program is to be able to allow the user to enter a problem (eg "my phone screen is blank") and for me to iterate through each word of the string and compare it to a dictionary, and the dictionary must be an external text file, I would like help on the dictionary aspect of this.我正在为学校做一个小型编程项目,我的程序的主要元素之一是能够允许用户输入一个问题(例如“我的手机屏幕是空白的”)并让我遍历每个单词字符串并将其与字典进行比较,并且字典必须是外部文本文件,我需要有关字典方面的帮助。 I have tried a few other methods from different posts of stack overflow but they do not seem to work.我从堆栈溢出的不同帖子中尝试了其他一些方法,但它们似乎不起作用。

Some lines of my dictionary include:我的字典中的一些行包括:

battery Have you tried charging your phone? You may need to replace your battery.
sound Your volume may be on 0 or your speakers may be broken, try using earphones.
blank Your screen may be dead, you may need a replacement.

Here, "battery,"sound" and "blank" are they keys with their respective values following on after, how do I plan on doing this?在这里,“电池”、“声音”和“空白”是它们各自的值的键,我打算怎么做呢?

Thank you!谢谢!


[edited code] [编辑代码]

def answerInput():
    print("Hello, how may I help you with your mobile device")
    a = input("Please enter your query below\n")
    return a

def solution(answer):
    string = answer
    my_dict = {}
    with open("Dictionary.txt") as f:
        for line in f:
            key, value = line.strip("\n").split(maxsplit=1)
            my_dict[key] = value
            for word in string.split():
                if word == my_dict[key]:
                    print(value)
            
process = 0
answer = answerInput()
solution(answer)
my_dict = {}  # defining it as a dictionary
with open("file.txt") as f:  # opening txt file
    for line in f:
        key, value= line.strip("\n").split(maxsplit=1)  # key is before first whitespace, value is after whitespace
        my_dict[key] = value

This will work well, something I have used personally.这会很好用,我个人使用过的东西。

It initiates a dictionary called my_dict , opens the file and for each line it strips \n from the line and splits it once only.它启动一个名为my_dict的字典,打开文件并为每一行从行中剥离\n并仅将其拆分一次。 This creates two values which we call key and value which we add to the dictonary in the form {key: value}这会创建两个值,我们称之为键和值,我们以{key: value}的形式添加到字典中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM