从其他列表中删除列表中的所有项目

时间:2016-11-13 16:49:13

标签: python

如果用户输入"搜索Facebook"然后程序将识别关键字" search"并且知道用户想要搜索网络。为了让程序搜索他们想要的内容,我需要从他们的输入中删除web_keys = ["search", "google", "bing", "internet", "online"]中的任何关键字,然后只使用输入搜索其他文本,在这种情况下" Facebook"。我使用下面的代码,但它不会从输入中删除关键字。如何从输入中删除任何关键字?

web_keys = ["search", "google", "bing", "internet", "online", "google"]

def web(q_input):
    while any(i in web_keys for i in q_input.split()):
        try:
            q_input.remove(web_keys)
        except AttributeError:
            break

        webbrowser.open('https://www.google.co.uk/webhp?hl=en&sa=X&ved=0ahUKEwio7-LNjqbQAhWDmBoKHTLJAHMQPAgD#hl=en&q='+q_input)
        print("Searching..." + "'" + q_input + "'")

1 个答案:

答案 0 :(得分:0)

这是一个适合我的版本 - 修复了一些缩进和其他问题:

web_keys = ["search", "google", "bing", "internet", "online"] # There was an extra google here

def web(q_input):
    for i in q_input.split(): # A simplified version breaking the while loop down to a for loop and an if
        if i in web_keys:
            q_input=q_input.replace(i,'') # Don't forget to assign the results back to q_input
    q_input=q_input.strip() # Remove leading and trailing extra spaces
    webbrowser.open('https://www.google.co.uk/webhp?hl=en&sa=X&ved=0ahUKEwio7-LNjqbQAhWDmBoKHTLJAHMQPAgD#hl=en&q='+q_input)
    print("Searching..." + "'" + q_input + "'")

web('google search Stack Overflow online')