我正在尝试从文件中读取并根据用户输入的问题返回解决方案。我已将文本文件保存在同一位置,这不是问题。目前,程序在我运行时崩溃并输入问题,例如"屏幕"。
代码
file = open("solutions.txt", 'r')
advice = []
read = file.readlines()
file.close()
print (read)
for i in file:
indword = i.strip()
advice.append (indword)
lst = ("screen","unresponsive","frozen","audio")
favcol = input("What is your problem? ")
probs = []
for col in lst:
if col in lst:
probs.append(col)
for line in probs:
for solution in advice:
if line in solution:
print(solution)
文本文件名为" solutions.txt"持有以下信息:
屏幕:将手机带到维修店,在那里他们可以更换损坏的屏幕。
无响应:按住电源按钮至少4秒钟,尝试重启手机。
冻结:按住电源按钮至少4秒钟,尝试重启手机。
音频:如果音频或声音不起作用,请到最近的维修店进行修理。
答案 0 :(得分:1)
你的问题让我想起了很多我的学习,所以我会尝试用大量的print
陈述来扩展你的学习,以便仔细考虑它的运作方式。这不是最有效或最稳定的方法,但希望有一些用途向前推进。
print "LOADING RAW DATA"
solution_dictionary = {}
with open('solutions.txt', 'r') as infile:
for line in infile:
dict_key, solution = line.split(':')
print "Dictionary 'key' is: ", dict_key
print "Corresponding solution is: ", solution
solution_dictionary[dict_key] = solution.strip('\n')
print '\n'
print 'Final dictionary is:', '\n'
print solution_dictionary
print '\n'
print 'FINISHED LOADING RAW DATA'
solved = False
while not solved: # Will keep looping as long as solved == False
issue = raw_input('What is your problem? ')
solution = solution_dictionary.get(issue)
""" If we can find the 'issue' in the dictionary then 'solution' will have
some kind of value (considered 'True'), otherwise 'None' is returned which
is considered 'False'."""
if solution:
print solution
solved = True
else:
print ("Sorry, no answer found. Valid issues are 'frozen', "
"'screen' 'audio' or 'unresponsive'")
want_to_exit = raw_input('Want to exit? Y or N? ')
if want_to_exit == 'Y':
solved = True
else:
pass
其他要点:
- 不要在任何地方使用'file'作为变量名。它是一个内置的python,可能会导致一些奇怪的行为,你很难调试https://docs.python.org/2/library/functions.html
- 如果您收到错误,请不要说“崩溃”,您应该提供某种形式的追溯,例如:
a = "hello" + 2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-6f5e94f8cf44> in <module>()
----> 1 a = "hello" + 2
TypeError: cannot concatenate 'str' and 'int' objects
祝你好运:)
答案 1 :(得分:0)
当我将“for in in file:”更改为“for i in read:”时,一切正常。
答案 2 :(得分:0)
仅输出以&#34;屏幕&#34;开头的行。忘记probs变量并将最后一个for语句改为
for line in advice:
if line.startswith( favcol ) :
print line
break
对于startswith()
功能,请参阅https://docs.python.org/2/library/stdtypes.html#str.startswith
并且:roganjosh的建议很有帮助。特别是请不要使用python关键字(例如文件)作为变量名称&#34;。我花了几个小时调试一些错误,例如&#34; file = ...&#34;或&#34; dict = ...&#34;。