因此,我尝试编写一个会询问您问题的程序,在该查询中搜索关键字,然后在找到某些关键字时输出解决方案。
到目前为止,这是我的代码:
def keyword_searcher():
user_query = input("Enter your problem:\n")
with open("user_query.txt", "a+") as query:
query.write(user_query.lower())
for line in query:
for word in line.split():
if word == "backlight" or "display" or "cracked" or "touchscreen":
f = open("Solutions1.txt", "r")
solution_one = f.read()
print ("Keyword for screen problem found:\n")
print (solution_one)
f.close()
elif word == "battery" or "charger" or "usb" or "charge":
f_two = open("Solutions2.txt", "r")
solution_two = f_two.read()
print ("Keyword for battery problem found:\n")
print(solution_two)
f.close()
elif word == "virus" or "hacked" or "infected" or "antivirus":
f_three = open("Solutions3.txt", "r")
solution_three = f_three.read()
print ("Keyword for virus problem found:\n")
print (solution_three)
else:
print ("Please be more specific\n")
keyword_searcher()
但是当我运行它时,我输入了我的问题但是没有输出。
编辑:根据建议,我的新代码是这样的。它考虑了文件位置(使用seek(0)
)并正确检查word
是否在关键字列表中:
def keyword_searcher():
user_query = input("Enter your problem:\n")
with open("user_query.txt", "a+") as query:
query.write(user_query.lower())
query.seek(0)
for line in query:
for word in line.split():
if word in ("backlight", "display", "cracked", "touchscreen"):
f = open("Solutions1.txt", "r")
solution_one = f.read()
print ("Keyword for screen problem found:\n")
print (solution_one)
f.close()
elif word in ("battery", "charger", "usb", "charge"):
f_two = open("Solutions2.txt", "r")
solution_two = f_two.read()
print ("Keyword for battery problem found:\n")
print(solution_two)
f.close()
elif word in ("virus", "hacked", "infected", "antivirus"):
f_three = open("Solutions3.txt", "r")
solution_three = f_three.read()
print ("Keyword for virus problem found:\n")
print (solution_three)
else:
print ("Please be more specific\n")
keyword_searcher()
问题是,它现在运行else
语句,为什么?
答案 0 :(得分:1)
首先想到的是您使用的逻辑OR不正确,您应该使用:
if word == "backlight" or word == "display" or word == "cracked" or word == "touchscreen"
您可以使用in
:
if word in ("backlight", "display", "cracked", "touchscreen")
解决此问题后,您可能会注意到,在您的情况下,使用a+
打开文件是不正确的,原因是Jim的回答中所述。将其更改为r
:
with open("user_query.txt", "r") as query
答案 1 :(得分:1)
更新:您的else
条款存在问题,不应再次致电keyword_searcher
。当您输入如下句子时:
Enter your problem:
My Problem is duh duh virus
它将再次调用该函数,并且不会检查该行的其余部分。相反,您应该继续使用line
中的下一个单词:
# how your else clause should look:
else:
print ("Please be more specific\n")
如果存在正确的关键字,现在将对每个字进行评估,其他条款将评估为True
。
您使用a+
打开这会打开"文件指针"到文件的末尾,所以没有行可以读取。如果你想迭代这些行,你应该用r
打开。
以下文件为例,请注意file.tell()
:
>>> with open("jupyter_notebook_config.py", "a+") as f:
... print(f.tell())
>>> 22821
>>> with open("jupyter_notebook_config.py", "r") as f:
... print(f.tell())
>>> 0
在第一种情况下,我们会在文件的末尾,因此for line in f
只是没有任何内容。在第二种情况下,我们所有行都可用,因此迭代它会产生文件中的行。
你可以做的是使用f.seek(0)
转到开头,然后开始迭代。