2016-05-24 39 views
-1

我对此代码有问题。它将一个字符串分割成一个列表并解析它。当我在列表中标识一个单词时,我想做一些事情。我已经看过IF语句,尽管它有逻辑意义,但代码只会生成语句“屏幕问题建议”,而不管输入的语句如何。我有点难以理解为什么我不能在条件语句中使用current_word。这有什么明显的错误吗?将字符串拆分为列表并在If语句中使用

text=str(input("enter your problem")) 
words = text.split() 

for current_word in words: 
    print(current_word) 
    if current_word=="screen": 
     print("screen problem advice") 
    elif current_word=="power": 
     print("power_problem advice ")  
    elif current_word=="wifi": 
     print("connection_problems advice") 

任何意见将不胜感激。

+0

这对我来说很好。请显示一个您认为不正确的示例输入输出对。 –

回答

0

如果我在我的机器上运行你的代码,它应该像它应该那样工作。

if elif elif elif else的一些简短模式是使用一些dict()并使用.get()-方法进行查找。

一些像这样的代码......

if word == "one": 
    variable = "11111" 
elif word == "two": 
    variable = "22222" 
elif word == "three": 
    variable = "33333" 
else: 
    variable = "00000" 

...可以写成某种形式更短:

variable = dict(
    one="11111", 
    two="22222", 
    three="33333" 
).get(word, "00000") 

回到你的问题。这里是一些示例。 我创建了一个detect函数,它产生所有检测到的建议。 在main函数中,建议只是打印出来。

请注意:.lower()ISSUES.get(word.lower()),所以它捕获“无线”,“无线上网”,“无线网络连接”的所有变化,...

def detect(message): 
    ISSUES = dict(
     wifi="network problem_advice", 
     power="power problem_advice", 
     screen="screen problem_advice" 
    ) 

    for word in message.split(): 
     issue = ISSUES.get(word.lower()) 
     if issue: 
      yield issue 


def main(message): 
    [print(issue) for issue in detect(message)] 

if __name__ == '__main__': 
    main("The screen is very big!") 
    main("My power supply is working fine, thanks!") 
    main("Wifi reception is very good today!") 

此外,我特意选择了一些奇怪的例子,你点到解决问题的一些基本问题。

简单的字符串匹配将不够,因为在这种情况下会产生误报。试着想一些其他的方法。