我正在为学校做一个小型的编程项目,我程序的主要内容之一是能够允许用户输入问题(例如“我的电话屏幕空白”),并让我遍历每个单词。字符串并将其与字典进行比较,并且字典必须是外部文本文件,我希望在字典方面有所帮助。我从堆栈溢出的不同帖子中尝试了一些其他方法,但是它们似乎不起作用。
我的字典中的某些行包括:
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.
在这里,“电池”,“声音”和“空白”是它们后面分别带有各自值的键,我该如何计划呢?
谢谢!
[编辑代码]
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}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句