python - 如何将文本文件转换为要在 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)
解决方案
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)}
推荐阅读
- java - 数据库运行状况指示器中的“hello”属性是什么意思?(弹簧执行器)
- javascript - 单击以在单击的位置打开 div
- java - 在 iText 7 的 html2pdf 中显示货币符号的简单方法
- sql - Oracle SQL中的查询查询
- sql-server - 如何完成推荐 - Azure 发送的“应为 SQL 服务器配置 Azure Active Directory 管理员”?
- linux - Heroku 上的 Electron 应用程序和与 libpng12.so.0 相关的错误:
- django - 在 Wagtail 中同时搜索页面和自定义模型
- javascript - 当 React js 中的任何状态发生变化时,如何停止重新渲染子组件?
- excel - 如何在不循环的情况下清除范围内货币格式的单元格
- memory - Kubernetes pod 内存使用明细