将字符串拆分为列表并在If语句中使用

时间:2016-05-24 13:21:23

标签: string list python-3.x if-statement

我的代码有问题。它将一个字符串拆分成一个列表并解析它。我想在列表中识别一个单词时做一些事情。我查看了IF语句,虽然从逻辑上看,代码只产生语句"屏幕问题建议"无论输入的句子如何。我有点难过为什么我不能在条件语句中使用current_word。这有什么明显的错误吗?

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")

非常感谢任何建议。

1 个答案:

答案 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()),因此它会捕获" wifi"," Wifi"," WiFi"的所有变体。 ,...

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!")

此外,我故意选择一些奇怪的例子来指出你试图解决问题的一些基本问题。

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

相关问题