Skip to main content
 首页 » 编程设计

python之如何计算字符串中的某些单词(不仅仅是一个单词),然后如果单词数量不同则输出不同的代码

2024年10月24日24cloudgamer

抱歉,这个问题很长,我不知道如何在不将其标记为重复的情况下具体措辞。无论如何,我正在尝试计算用户输入的一组关键字,这些关键字被写入文本文件。这是代码:

import os 
def keyword_searcher(): 
user_query = input("Enter your problem:\n") 
with open("user_query.txt", "a+") as query: 
    query.write(user_query.lower()) 
    query.seek(0) 
    for line in query: 
        for word in line.split(): 
            if word in ("backlight", "display", "cracked", "touchscreen"): 
                with open("Solutions1.txt", "r") as f: 
                    solution_one  = f.read() 
                    print ("Keyword for screen problem found:\n") 
                    print (solution_one) 
            elif word in ("battery", "charger", "usb", "charge"): 
                with open("Solutions2.txt", "r") as f_two: 
                    solution_two = f_two.read() 
                    print ("Keyword for battery problem found:\n") 
                    print(solution_two) 
            elif word in ("virus", "hacked", "infected", "antivirus"): 
                with open("Solutions3.txt", "r") as f_three: 
                    solution_three = f_three.read() 
                    print ("Keyword for virus problem found:\n") 
                    print (solution_three) 
            else: 
                pass 
keyword_searcher() 
os.remove("user_query.txt") 

我的问题是,当用户输入多个关键字时,它会输出那么多次代码,而我只需要一次。我该如何解决这个问题?

请您参考如下方法:

for word in line.split(): 
    if word in ("backlight", "display", "cracked", "touchscreen"): 
       ... 

意味着您将在循环的每次迭代中检查一个词,因此如果有多个词匹配,您将得到重复项。要仅在列表中存在至少一个单词时执行此操作,请使用 sets:

for line in query: 
    words = set(line.split()) 
    if words & {"backlight", "display", "cracked", "touchscreen"}: 
        ... 

或者,你可以做类似的事情

for line in query: 
    words = line.split() 
    if any(word in ("backlight", "display", "cracked", "touchscreen") for word in words): 
        ... 

这可能更容易阅读,但会更慢。