首页 > 解决方案 > 如何将文本文件转换为要在 Python 中使用的字典?

问题描述

我正在为学校做一个小型编程项目,我的程序的主要元素之一是能够允许用户输入问题(例如“我的手机屏幕是空白的”)并让我遍历每个单词字符串并将其与字典进行比较,并且字典必须是外部文本文件,我需要有关字典方面的帮助。我从堆栈溢出的不同帖子中尝试了其他一些方法,但它们似乎不起作用。

我的字典中的一些行包括:

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.

在这里,“battery”、“sound”和“blank”是它们各自的值的键,我打算怎么做呢?

谢谢!


[编辑代码]

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)

标签: pythondictionary

解决方案


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

这会很好用,我个人使用过的东西。它启动一个名为 的字典my_dict,打开文件,并为每一行\n从行中剥离并仅拆分一次。这会创建两个值,我们称之为键和值,我们将它们添加到表单中的字典中{key: value}

或者,使用 dict 理解

with open("file.txt") as f:  # opening txt file
    my_dict = {k: v for k,v in (line.strip("\n").split(maxsplit=1) for line in f)}

推荐阅读