在.split()中具有if语句的多个可能选项

2024-04-26 06:16:30 发布

您现在位置:Python中文网/ 问答频道 /正文

抱歉,问题解释得不好,但我的代码是:

import csv

file = open("problems_solutions.csv","a+")
name = input("What is your name?")
file.write(name+",")
problem = input("Enter the problem that you have with your mobile phone.").lower()
file.write(problem+"\n")
file.close()

基本上,它会询问用户的姓名和他们遇到的问题,并将其写入.csv;这一部分非常有效。你知道吗

if ["sound","speaker","volume","audio","earphone","earphones","headphones","headphone"] in problem.split():
    file=open("nosound Solutions.txt","rb")
    print(file.read())
    file.close()

if ["battery","charge","charged","low"] in problem.split():
    file = open("lowbattery Solutions.txt","r")
    print(file.read())
    file.close()

然而,当用户输入一个问题,如“我的声音不工作”,之后什么也不会发生-没有输出,什么也没有。我试过去掉方括号,用“or”替换逗号,但是由于我有多个if语句用于不同的解决方案,它反而打印代码中的每个文本文档。你知道吗

文本文档包含解决方案,例如“尝试重新启动手机”、“检查手机是否静音”

如果需要任何其他信息,那么我非常乐意提供;这个问题让我很沮丧,我找不到如何解决它。你知道吗

谢谢


Tags: csv代码用户nameincloseinputyour
3条回答

您当前正在list中查找list。这只查找文本对象。[1, 2]将在[3, [1, 2], 9]中,但不在[1, 2, 3]中。您要寻找的实际概念是一组交叉点:

>>> problems = {"battery","charge","charged","low"}
>>> user_input = set('the battery is broken'.split())
>>> problems & user_input
{'battery'}

当可用问题和用户输入之间存在一些共同点时,您可以执行if problems & user_input:来执行代码块。你知道吗

我相信问题是你在寻找一个数组中的一个数组。。。但我认为你想在数组中寻找一个字符串?你知道吗

这似乎对我有用:

problem = "My sound isn't working"
for i in ["sound","speaker","volume","audio","earphone","earphones","headphones","headphone"]:
  if i in problem.split():
    file=open("nosound Solutions.txt","rb")
    print(file.read())
    file.close()
    break

如前所述,您询问是否在另一个列表中找到整个列表。如果problem.split()等于[["battery","charge","charged","low"], 'some', 'other', 1, 'values']之类的值(显然永远不会是),那么Check就是真的。你知道吗

要进行所需的检查,可以使用^{}内置函数。你知道吗

if any(word in problem.split() for word in ["battery","charge","charged","low"]):
    pass  # do something

相关问题 更多 >

    热门问题