2017-02-12 38 views
0

我最近发现了这个代码,但一直在努力研究它是如何工作的。 “111.txt”是一个带有列表行的文本文件,其中每行上的列表的第一部分是解决方案,该列表中的相应单词是解决方案的关键词。我了解除了第8行(solutions[i[-1]] ...)之外的大部分内容。我一直在查找使用的不同模块,但我仍然不明白该线路是什么以及它是如何工作的。我对Python的使用很新,所以如果可能的话,我会非常感谢这一行的简单解释。提取文本文件中的第一个单词,然后提取相应的单词?

在此先感谢!

questionbank = [] 
with open ('111.txt') as questions: 
    for line in questions: 
     questionbank.append(line.strip().split(',')) 

solutions = {} 
for i in questionbank: 
    solutions[i[-1]] = i[0:len(i)-1] 

def phone_problem(): 
    n = 2 
    while n <3: 
     problem = input("Phone problem?") 
     for d,v in solutions.items(): 
      if any(word in problem for word in v): 
       print(d) 
       n = 4 
      else: 
       continue 

phone_problem() 

“112.txt” 的例子:

put your phone is rice, wet, damp, water, puddle 
replace you screen, screen, crack, smash, shatter... 

更新: 我在你的代码添加了,但它仍然简化版,输出的解决方案。无论我输入什么问题,它都会继续运行while循环。我真的不确定为什么,但当您定义解决方案时可能会这样做。

import webbrowser,time 
url = "https://www.google.co.uk/webhp?hl=en&sa=X&ved=0ahUKEwjNuLiL1vHRAhVjD8AKHdFEAiEQPAgD&gws_rd=cr&ei=zUiTWKKpF8P_UoSambgO#hl=en&q=" 
problem = input("What is the problem with you device?") 
split = problem.split(" ") 
keyList = [] 

def other(): 
     print("no solution") 

questionbank = [] 


with open ('111.txt') as questions: 
    for line in questions: 
     questionbank.append(line.strip().split(',')) 
# the following line are probably the source of the problem(up to calling the phone_problem function) 
solutions = {question[0]:question[1:] for question in questionbank} 


def phone_problem(): 
    while True: 
     for solution, key_words in solutions.items(): 
      if any(word in problem for word in key_words): 
       print(solution) 
       return 

phone_problem() 
if keyList == []: 
    with open("counter.txt", "r") as file: 
     for lines in file: 
       number = lines[0] 
    file.close() 
    text_file = open("help.txt", "w") 
    text_file.write(str(int(number)+1)) 
    text_file.write("\n{}      {}        {}         {}       {}".format(number,devType,brand,device,problem)) 
    text_file.close() 
    other() 
keyList = list(set(keyList)) 
for i in keyList: 
    print("Solution:",i) 
+3

请从111.txt中添加示例输入 – ppasler

回答

1

答案就在下面的评论...

solutions = {} 
for i in questionbank: 
    # i = ['put your phone is rice', 'wet', 'damp', 'water', 'puddle'] 
    # i[-1] means last thing in list = 'puddle' 
    # i[0:len(i)-1] means everything in i except the last element 
    #    which could be rewritten as i[:-1] 
    solutions[i[-1]] = i[0:len(i)-1] 
    # solutions['puddle'] = ['put your phone is rice', 'wet', 'damp', 'water'] 

我认为该代码是马车。解决方案的关键不应该是该行的第一个元素?代码可以写得更好,如下所示。

solutions = {question[0]:question[1:] for question in questionbank} 

def phone_problem(): 
    while True: 
     problem = input("Phone problem?") 
     for solution, key_words in solutions.items(): 
      if any(word in problem for word in key_words): 
       print(solution) 
       return 
+0

非常感谢你,这真的帮助我! – Joel

相关问题