使用文本文件为输入创建对应的打印语句

时间:2016-05-08 11:37:01

标签: python input text-files

我的问题是我想要创建一个程序,该程序从用户接收输入,然后从文本文件中获取与用户输入的内容相对应的响应。例如,如果用户输入"我的SIM卡没有工作"该计划将回应说"购买新的SIM卡"。 我也可以用数组做这个,我已经开始尝试用这些数组创建一些东西了。

problems = ["My battery isn't working","My sim isn't working","My screen is cracked"]
solutions = ["Buy a new battery","Call your service provider","Contact the manufacturer"]
issue = input("What is the issue with your phone? ")
if (issue == problems[0])
    print(solutions[0])

等等。但我真的想合并文本文件,因为这会使我的代码变得更复杂。

1 个答案:

答案 0 :(得分:1)

选项是将数据保存到文本文件,然后读取并评估它。我会用字典替换数组,因为它更符合你的目的。

首先,将字典保存到文本文件中:

path = 'dict.txt'
solutions = {
    "My battery isn't working": "Buy a new battery",
    "My sim isn't working": "Call your service provider",
    "My screen is cracked": "Contact the manufacturer"
}
openFile = open(path, 'wt')
openFile.write(repr(solutions))
openFile.close()

然后,加载,评估和使用您的代码:

path = 'dict.txt'
openFile = open(path, 'rt')
stringDict = openFile.read()
openFile.close()

solutions = eval(stringDict)
issue = input("What is the issue with your phone? ")
print(solutions[issue])

使用repreval函数可能是更简单的方法,但最好使用python的标准{{3来转储和加载JSON格式的字典库或任何第三方库,例如json