如何添加两个解决方案

时间:2016-06-29 09:46:26

标签: python

所以这段代码可行,但我希望它能从文本文件中打印两个解决方案。问题包括尝试在文本文件中打印出两行,当关键字与if 'word' == something then print一起使用时,我想打印两行。任何帮助,将不胜感激。我尝试了各种不同的东西。

problem = False

while problem == False:

    foo = open("solutions.txt","r")

    print("What is wrong with your device?")

    issue=input()

    if (('wet' in issue) or ('water' in issue)):
        solutions = foo.readlines()
        print(solutions[0])
        problem = True

    if (('cracked' in issue) or ('dropped' in issue)):
        solutions = foo.readlines()
        print(solutions[1])
        problem = True

2 个答案:

答案 0 :(得分:0)

如果解决方案始终是固定的,则应移动文件打开并在循环外读取。关键字和解决方案索引之间的匹配可以使用字典来完成。

problem = False

foo = open("solutions.txt","r")
solutions = foo.readlines()

Problemlistdict = {'wet':0, 'water':0, 'dropped':1, 'sim card':2} #etc..etc

while problem == False:

    print("What is wrong with your device?")

    issue=input()

    sol = set()

    for k in Problemlistdict.keys():
        if k in issue:
            sol.add(Problemlistdict[k])

结果将是一个包含所有相关解决方案行索引的集合。

答案 1 :(得分:0)

为您的行选择添加一个停止索引:

solutions[0:1]将返回文件的前两行,而不仅是第一行。

或者对于没有紧随其后的两行,请执行:

solutions[2] + solutions[7]

请参阅F. Lundbergh的“Accessing lists”作为无休止的Python文档解释此内容的任意示例。

此外,您可以在第一个if之后将elif更改为else并添加with,以便在用户的输入中找不到您选择的任何问题。< / p>

建议使用open代替open,以确保文件正常关闭。如果你使用Python&lt; 2.7,你必须使用close,不要再忘记docker cp <containerId>:/file/path/within/container /host/path/target

相关问题