Python 根据用户输入,从csv文件运行特定行

Python 根据用户输入,从csv文件运行特定行,python,csv,input,keyword,Python,Csv,Input,Keyword,如何根据用户输入从csv文件运行特定行。 我的代码要求用户输入其手机的问题,如果用户输入water has spilled,则会识别关键字water或spilled,并打印存储在csv中的解决方案。但是,我在那里为不同的关键字存储了许多解决方案。如果您的问题/解决方案以这种方式写入文件: Problems1\nSolution1\nProblems2\nSolution2 其中: Problems1 Solution1 Problems2 Solution2 您可以尝试以下代码: probl

如何根据用户输入从csv文件运行特定行。
我的代码要求用户输入其手机的问题,如果用户输入water has spilled,则会识别关键字water或spilled,并打印存储在csv中的解决方案。但是,我在那里为不同的关键字存储了许多解决方案。

如果您的问题/解决方案以这种方式写入文件:

Problems1\nSolution1\nProblems2\nSolution2
其中:

Problems1
Solution1
Problems2
Solution2
您可以尝试以下代码:

problem = input ('What is your problem ? ')

with open ('keywords.txt', 'r') as myfile:
    text = myfile.read()

list_of_problems_and_solutions = text.split('\n')

for i in range (0, len(list_of_problems_and_solutions )-1, 2):
    if problem in list_of_problems_and_solutions [i]
    print (list_of_problems_and_solutions [i + 1])

>>> What is your problem ? Problems1
Solution1
问题和解决方案的
列表将类似
['Problems1','Solution1','Problems2','Solution2']
范围内i的
(0,len(问题和解决方案列表)-1,2):
函数将从索引0到末尾遍历列表,步骤为2。
如您所见,当我键入
Problems1
作为我的问题时,Python返回
Solution1
。您只需替换为关键字/解决方案即可

首先将数据集重新编写为:

'turn', 'on', 'off'
put it on charger
'small', 'text'
go on settings.
...
然后搜索问题并打印下一行

problems = input("What is the problem?")

with open("/path/myfile.csv") as myfile:
    file = iter(myfile.readlines())
    for line in file:
        if any(word in line for word in problems.split()):
            print(next(file))
            break

keywords.txt
中的行在关键字和解决方案之间交替,对吗?此外,我建议使用json作为更好的信息存储方式:@BurningKarl你能看看我的另一个question@stovfl你能查一下我的另一本书吗question@sufiya当前位置看不到任何其他问题。你为什么要删除你的
代码
,把它带回来。谢谢!!!是否存在从句子中检测到关键字“off”的情况。当我输入包含关键字的句子时,程序不起作用。如果我自己输入的话,效果会非常好:)@tasos很高兴它能为你工作!为了处理一个给定的句子,一个想法是将句子分成几个单词,然后独立地搜索每个单词。您可以将
if problems…
行替换为
if any(word in line for word in problems.split()):
出现错误。它说问题并没有被定义为@tasost当你们在复制时可能出现了拼写错误。这是
问题
不是
问题
:)如果有(问题中一个字一个字地排列。split()):输入(“问题出在哪里?”)小心你的
i+=1
。您可以轻松检查枚举([“a”、“b”、“c”、“d”])中i的
:print(i,end=“”);i+=1
给出
0 1 2 3
而不是
0 2
正确,此处的范围函数更合适请更改您的描述,因为阅读您描述中的
i+=1
而不在实际代码中看到它会让人困惑。另外,此处未定义
liste
,请将其更改为
listof\u problems\u和\u solutions
Oops抱歉,我有it@Guil23你能查一下我的另一个问题吗